Victoria Price
Victoria Price

Reputation: 637

Writing mouse location to QTableWidget

How can I write append mouse click coordinates to a QTableWidget with each click? I already have the QMouseEvent to display the coordinates in a QLabelItem, but I would like to add a row with the coordinates of each click. Is this possible? I know I would need to use setItem() but how do I attach this to the existing mouse click event?

Here's the event filter that I have for the mouse clicks:

   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))

Upvotes: 0

Views: 644

Answers (2)

Pierre GM
Pierre GM

Reputation: 20329

Assuming that model=QTableView.model(), you could append a new row to your table with something like:

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

If you have a QTableWidget and not a QTableView, you could use the same MO:

  • Append a new row with self.insertRow(self.rowCount())
  • Use the .setItem method to modify the data of your last row. You could use for example QTableWidgetItem("({0},{1})".format(x,y)), or whatever string you like to represent your tuple of coordinates.

However, I'd advise you to start using a QTableViews instead of a QTableWidget, as it offers far more flexibility.

Upvotes: 1

ekhumoro
ekhumoro

Reputation: 120578

Assuming you have a two-column table for the x,y values, and you want to append a new row with each click:

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)

Upvotes: 1

Related Questions