Python PyQt4 QTableWidget CellWidget Roll列值

时间:2014-04-02 04:45:23

标签: python pyqt pyqt4 qtablewidget

我有一个QTablWidget,其中包含以下属性:

        mytable.setEditTriggers(QtGui.QTableWidget.NoEditTriggers)
        mytable.setSelectionBehavior(QtGui.QTableWidget.SelectRows)
        mytable.setSelectionMode(QtGui.QTableWidget.SingleSelection)
        mytable.horizontalHeader().setStretchLastSection(True)
        mytable.verticalHeader().hide()

在我桌子的每一行上,QPushButton设置为CellWidget,如下所示:

enter image description here

当用户按下任何按钮时,有没有办法获取Row number所在的QPushButton表格?

例如,如果用户点击表格QPushButton上的row 2,则会返回值2.

编辑2

根据其中一个答案,我已将代码更新为:但我仍然没有得到任何东西。我哪里出错了?我试图打印self.table.itemAt(button.pos())的输出,我得到None

from PyQt4 import QtGui,QtCore
import sys

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self,parent)
        self.table = QtGui.QTableWidget()
        self.table.setColumnCount(3)
        self.setCentralWidget(self.table)
        data1 = ['orange','apple','banana','lemon']
        data2 = ['3','4','5.5','2']

        self.table.setRowCount(4)

        for i in range(4):
            item1 = QtGui.QTableWidgetItem(data1[i])
            self.table.setItem(i,0,item1)
            item2 = QtGui.QTableWidgetItem(data2[i])
            self.table.setItem(i,1,item2)
            self.button = QtGui.QPushButton('TEST')
            self.button.clicked.connect(self.handleButtonClicked)
            self.table.setCellWidget(i,2,self.button)

    def handleButtonClicked(self):
        button = self.sender()
        item = self.table.itemAt(button.pos())
        if item is not None:
            print (item.row(),item.column())


def Main():
    app = QtGui.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    app.exec_()

if __name__ == '__main__':
    Main()

1 个答案:

答案 0 :(得分:1)

如果您可以获得对单击按钮的引用,则QTableView.indexAt可用于获取相应的索引:

    button.clicked.connect(self.handleButtonClicked)
    ...        

    def handleButtonClicked(self):
        button = QtGui.qApp.focusWidget()
        # or button = self.sender()
        index = self.table.indexAt(button.pos())
        if index.isValid():
            print(index.row(), index.column())