PyQt:QTableWidg中的复选框

2024-10-01 17:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下代码在我的QTableWidget的第9列中放置一个复选框

chkBoxItem = QtGui.QTableWidgetItem()
chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
chkBoxItem.setCheckState(QtCore.Qt.Unchecked)       
table.setItem(rowNo,9,chkBoxItem)

其中table是我的QtTableWidget。我需要将复选框所在的行添加到列表中。。我到底是怎么做到的?

谨致问候


Tags: 代码tableqt复选框qtguisetitemqtcoreqtablewidget
1条回答
网友
1楼 · 发布于 2024-10-01 17:23:53

一种方法是:

  1. 将表的^{}信号连接到处理程序

  2. 在处理程序中测试已单击项的^{}

  3. 如果选中该项,请将其^{}添加到列表中

示例代码:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        QtGui.QWidget.__init__(self)
        self.table = QtGui.QTableWidget(rows, columns, self)
        for column in range(columns):
            for row in range(rows):
                item = QtGui.QTableWidgetItem('Text%d' % row)
                if row % 2:
                    item.setFlags(QtCore.Qt.ItemIsUserCheckable |
                                  QtCore.Qt.ItemIsEnabled)
                    item.setCheckState(QtCore.Qt.Unchecked)
                self.table.setItem(row, column, item)
        self.table.itemClicked.connect(self.handleItemClicked)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        self._list = []

    def handleItemClicked(self, item):
        if item.checkState() == QtCore.Qt.Checked:
            print('"%s" Checked' % item.text())
            self._list.append(item.row())
            print(self._list)
        else:
            print('"%s" Clicked' % item.text())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window(6, 3)
    window.resize(350, 300)
    window.show()
    sys.exit(app.exec_())

相关问题 更多 >

    热门问题