There are a number of approaches that could solve this problem. Some can involve cursor location, and others can get into the table events and signals. A problem with using the QCursor to solve this, is if someone triggers the button with the keyboard as opposed to the mouse click, which means the cursor position might not reflect the correct row.
Since you are already using the high-level QTableWidget
, then here is a really simple way to do it:
from functools import partial
class Table(QtGui.QWidget):
def __init__(self):
super(Table, self).__init__()
self.table = QtGui.QTableWidget(3, 2, self)
for row in xrange(3):
item = QtGui.QTableWidgetItem("Item %d" % row)
self.table.setItem(row, 0, item)
button = QtGui.QPushButton("X", self.table)
self.table.setCellWidget(row, 1, button)
button.clicked.connect(partial(self._buttonItemClicked, item))
layout = QtGui.QHBoxLayout(self)
layout.addWidget(self.table)
def _buttonItemClicked(self, item):
print "Button clicked at row", item.row()
In this example, we just bake the item of the first column into the clicked callback, so when you click them they have a reference for asking the row number. The approach would be different for lower level model/view.