首页 > 解决方案 > QTableView 选择更改

问题描述

在这个上搜索了一段时间,但我似乎找不到任何东西。在选择更改时需要 QTableView 的信号。试过tbl_view.itemSelectionChanged.connect(self.select_row)但编译器抱怨这不存在。我还需要从选定的行中检索数据。有人可以指出我正确的方向吗?

标签: pythonpython-3.xpyqtpyqt5qtableview

解决方案


itemSelectionChanged是一个QTableWidget信号,因为在该类中存在 item 的概念,但在 QTableView 中不存在。如果是QTableViewQListView并且QTreeView具有称为selectionModel()返回跟踪所选元素的模型的方法,并且该模型在选择中有一个调用的信号selectionChanged(),例如:例如:

from PyQt5 import QtCore, QtGui, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        table_view = QtWidgets.QTableView()
        self.setCentralWidget(table_view)

        model = QtGui.QStandardItemModel(5, 5, self)
        table_view.setModel(model)

        for i in range(model.rowCount()):
            for j in range(model.columnCount()):
                it = QtGui.QStandardItem(f"{i}-{j}")
                model.setItem(i, j, it)

        selection_model = table_view.selectionModel()
        selection_model.selectionChanged.connect(self.on_selectionChanged)

    @QtCore.pyqtSlot('QItemSelection', 'QItemSelection')
    def on_selectionChanged(self, selected, deselected):
        print("selected: ")
        for ix in selected.indexes():
            print(ix.data())

        print("deselected: ")
        for ix in deselected.indexes():
            print(ix.data())


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

推荐阅读