Chris Aung
Chris Aung

Reputation: 9532

How to find out to which QTableWidget a QPushbutton belongs to?

I have two QTableWidgetItems. Each has multiple QPushButtons set as cell widget in it.

Currently, for one QTableWidget I am using self.sender() to find out the row and column of the button that is being pressed:

button = self.sender()
index = self.Table.indexAt(button.pos())
currentRow = index.row()
mydata = str(self.Table.item(currentRow, 2).text())

However, I would like to connect the QpushButtons of both tables to the same function. So, if I have table A and table B both having the QPushButtons connected to the same function.

How can I then know if a button belongs to table A or table B when it is being clicked?

Upvotes: 2

Views: 3548

Answers (2)

NoDataDumpNoContribution
NoDataDumpNoContribution

Reputation: 10864

As Matyas Kuti says you can use parent. I made an example for it.

from PySide import QtGui

class MyTableWidget(QtGui.QTableWidget):

    def __init__(self):
        super().__init__(None)
        button = QtGui.QPushButton('Click me', self)
        button.clicked.connect(self.buttonClicked)
        self.setCellWidget(2, 1, button)

    def buttonClicked(self):
        button = self.sender()
        print(button.parent() is self)


app = QtGui.QApplication([])
table = MyTableWidget()
table.show()
app.exec_()

The output is True when clicked on the button. Example is in Python 3.X and PySide but should apply to all Pythons and PyQt as well.


edit: In case you did not inherit directly from QTableWidget but both QTableWidget and the buttons are children of another object, just store a reference to the table in the common parent under a known name (for example "table") and then access like:

 button.parent().table

Upvotes: 4

Mátyás Kuti
Mátyás Kuti

Reputation: 830

If the parent-child relationship is properly set between the button and the table widget (most likely it is) you can use the QPushButton's parent() method to access the QTableWidgetItem and use the same function on the item to access the QTableWidget.

Upvotes: 1

Related Questions