[英]How to find out to which QTableWidget a QPushbutton belongs to?
I have two QTableWidgetItems
. 我有两个QTableWidgetItems
。 Each has multiple QPushButtons
set as cell widget in it. 每个都有多个QPushButtons
设置为其中的单元小部件。
Currently, for one QTableWidget
I am using self.sender()
to find out the row and column of the button that is being pressed: 当前,对于一个QTableWidget
我正在使用self.sender()
来找出所按下按钮的行和列:
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. 但是,我想将两个表的QpushButtons
连接到相同的函数。 So, if I have table A and table B both having the QPushButtons connected to the same function. 因此,如果我的表A和表B都具有连接到同一功能的QPushButtons。
How can I then know if a button belongs to table A or table B when it is being clicked? 当单击按钮时,如何知道按钮是否属于表A或表B?
As Matyas Kuti says you can use parent
. 正如Matyas Kuti所说,您可以使用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. 单击按钮时,输出为True
。 Example is in Python 3.X and PySide but should apply to all Pythons and PyQt as well. 示例在Python 3.X和PySide中使用,但也应适用于所有Python和PyQt。
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: 编辑:如果您没有直接从QTableWidget
继承,但是QTableWidget
和按钮都是另一个对象的子代,只需将对表的引用以已知名称(例如“ table”)存储在公共父级中,然后像这样进行访问:
button.parent().table
如果在按钮和表窗口小部件之间正确设置了父子关系(很可能是这样),则可以使用QPushButton的parent()
方法访问QTableWidgetItem,并在该项目上使用相同的函数访问QTableWidget。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.