QTableView 选择更改

Elc*_*_91 6 python pyqt qtableview python-3.x pyqt5

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

eyl*_*esc 7

itemSelectionChanged是一个QTableWidget信号,因为在该类中存在 item 的概念,但在 QTableView 中不存在。在的情况下QTableViewQListViewQTreeView已调用的方法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_())
Run Code Online (Sandbox Code Playgroud)