python - QTableView 选择改变

标签 python python-3.x pyqt pyqt5 qtableview

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

最佳答案

itemSelectionChanged是一个 QTableWidget 信号,因为在该类中存在项的概念,但在 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_())

关于python - QTableView 选择改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52778141/

相关文章:

python-3.x - 无法理解语法href =\“\

javascript - 在 PyQt 应用程序中缓存 QtWebkit 小部件的外部 JavaScript

python - 需要用 PyQt4 实例化 QWidget

python - 将音频文件保存到所需路径

python - 如果不存在,写入模式会创建一个新文件吗?

python - 如何设置 tkinter 比例 slider 的颜色?

python - 我的程序有错误,无法找出它不起作用的原因

python - 循环遍历python中的列表以创建多个文件

python - Django Rest Framework 'list' 对象没有属性值

python - 循环帮助: it doesn't wait for loadFinished SIGNAL in PyQt4