将鼠标位置写入QTableWidget

时间:2012-08-31 15:03:51

标签: python pyqt qtablewidget

如何在每次点击时将鼠标点击坐标附加到QTableWidget?我已经有QMouseEvent来显示QLabelItem中的坐标,但我想添加一行,其中包含每次点击的坐标。这可能吗?我知道我需要使用setItem(),但如何将其附加到现有的鼠标点击事件?

以下是鼠标点击的事件过滤器:

   def eventFilter(self, obj, event):
        if obj is self.p1 and event.type() == event.GraphicsSceneMousePress:
            if event.button()==Qt.LeftButton:
                pos=event.scenePos()
                x=((pos.x()*(2.486/96))-1)
                y=(pos.y()*(10.28/512))
                self.label.setText("x=%0.01f,y=%0.01f" %(x,y))
       #here is where I get lost with creating an iterator to append to the table with each click
             for row in range(10):
                for column in range(2):
                    self.coordinates.setItem(row,column,(x,y))

2 个答案:

答案 0 :(得分:1)

假设model=QTableView.model(),您可以使用以下内容向表中添加新行:

nbrows = model.rowCount()
model.beginInsertRows(QModelIndex(),nbrows,nbrows)
item = QStandardItem("({0},{1})".format(x,y))
model.insertRow(nbrows, item.index())
model.endInsertRows()

如果您有QTableWidget而不是QTableView,则可以使用相同的MO:

  • 使用self.insertRow(self.rowCount())
  • 附加新行
  • 使用.setItem方法修改最后一行的数据。您可以使用例如QTableWidgetItem("({0},{1})".format(x,y))或您喜欢的任何字符串来表示您的坐标元组。

但是,我建议您开始使用QTableView而不是QTableWidget,因为它提供了更大的灵活性。

答案 1 :(得分:1)

假设您有x,y值的双列表格,并且您希望每次点击都附加一个新行:

def eventFilter(self, obj, event):
    if obj is self.p1 and event.type() == event.GraphicsSceneMousePress:
        if event.button() == Qt.LeftButton:
            pos = event.scenePos()
            x = QtGui.QTableWidgetItem(
                '%0.01f' % ((pos.x() * 2.486 / 96) - 1))
            y = QtGui.QTableWidgetItem(
                '%0.01f' % (pos.y() * 10.28 / 512))
            row = self.coordinates.rowCount()
            self.coordinates.insertRow(row)
            self.coordinates.setItem(row, 0, x)
            self.coordinates.setItem(row, 1, y)
相关问题