python - PYQT如何在QTableView的每一行添加复选框

标签 python pyqt pyqt4 pyqt5 qt-designer

我有一个简单的 .xlsx 文件,我将其内容加载到我的 qtableview 中。我的代码是这样的:

import xlrd
from PyQt5 import QtCore, QtGui, QtWidgets, uic

form_class = uic.loadUiType("SearchView.ui")[0]  # Load the UI

app = None
myWindow = None
dic_messages = dict()


class MyWindowClass(QtWidgets.QMainWindow, form_class):
    def __init__(self, fileName, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.gui = form_class
        self.fileName = fileName
        self.model = QtGui.QStandardItemModel(self)
        self.tableView.setModel(self.model)
        self.fn_load_messages()

    def fn_load_messages(self):
        workbook = xlrd.open_workbook('sample.xlsx')
        worksheet = workbook.sheet_by_name('sample_sheet')

        for i in range(0, worksheet.nrows):
            dic_messages[i + 1] = (worksheet.cell(i, 0).value, worksheet.cell(i, 1).value, worksheet.cell(i, 2).value, worksheet.cell(i, 3).value, worksheet.cell(i, 4).value)
            i += 1

        rowPosition = self.tbl_messages.rowCount()
        self.tbl_messages.insertRow(rowPosition)

      return

def main():
    global app, myWindow
    app = QtWidgets.QApplication(sys.argv)
    myWindow = MyWindowClass('sample.xlsx')
    myWindow.show()
    app.exec_()


if __name__ == '__main__':
    main()

我想在每一行中添加一个复选框列,然后我想选中或取消选中我想要的每一行。我在我的代码中添加了以下部分,但复选框未激活:

self.tableView.setItemDelegateForColumn(0 , CheckBoxDelegate(self))
class CheckBoxDelegate(QtWidgets.QStyledItemDelegate):
 def paint(self, painter, option, index):
    check_box_style_option = QtWidgets.QStyleOptionButton()
    check_box_style_option.rect = self.getCheckBoxRect(option)
    check_box_style_option.state = QtWidgets.QStyle.State_Enabled
    QtWidgets.QApplication.style().drawControl(QtWidgets.QStyle.CE_CheckBox, 
    check_box_style_option, painter)

def getCheckBoxRect(self, option):
    check_box_style_option = QtWidgets.QStyleOptionButton()
    check_box_rect = QtWidgets.QApplication.style().subElementRect(QtWidgets.QStyle.SE_CheckBoxIndicator, check_box_style_option, None)
    check_box_point = QtCore.QPoint (option.rect.x() +
                        option.rect.width() / 2 -
                        check_box_rect.width() / 2,
                        option.rect.y() +
                        option.rect.height() / 2 -
                        check_box_rect.height() / 2)
    return QtCore.QRect(check_box_point, check_box_rect.size())

我该怎么做? 谢谢。

最佳答案

您不在 View 中设置它,而是在项目和模型中设置。像这样:

#!/usr/bin/env python

from PyQt5 import QtWidgets, QtGui

class MyWidget(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.tableModel = QtGui.QStandardItemModel(self)
        self.tableModel.itemChanged.connect(self.itemChanged)

        item = QtGui.QStandardItem("Click me")
        item.setCheckable(True)
        self.tableModel.appendRow(item)

        self.mainLayout = QtWidgets.QVBoxLayout()
        self.setLayout(self.mainLayout)

        self.tableView = QtWidgets.QTableView()
        self.tableView.setModel(self.tableModel)
        self.mainLayout.addWidget(self.tableView)

    def itemChanged(self, item):
        print("Item {!r} checkState: {}".format(item.text(), item.checkState()))


def main():
    app = QtWidgets.QApplication([])

    win = MyWidget()
    win.show()
    win.raise_()
    app.exec_()

if __name__ == "__main__":
    main()

关于python - PYQT如何在QTableView的每一行添加复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43953021/

相关文章:

python - Matplotlib 小部件中的多个图

python - 如何从 QTableWidget 项目中获取选定的标题标签?

python - 需要帮助连接类中的 Connections

python - 为什么这个 Google App Engine ndb 祖先查询不起作用?

python 3.7 : Initialize objects with dataclasses module?

python - pyqt:如何删除小部件?

python-3.x - 如何验证 QTableWidget 中的单元格?

windows - 在 Qt 中禁用进度条动画

python - Pandas 奇怪的 SettingWithCopyWarning 警告

python - 将结果从 Python 返回到 Vba