【问题标题】:PyQt QTableView get start index of cell spanning multiple columns?PyQt QTableView 获取跨多列的单元格的起始索引?
【发布时间】:2019-09-08 22:08:33
【问题描述】:

我有一个 QTableView,其中的单元格设置了 1、2 和 4 的列跨度。我正在尝试这样做,以便在选择一个单元格时,它上面的所有单元格也会自动选择,所以在示例中点击下方的x 将选择所有这些单元格:

我尝试通过遍历所有选定的索引并选择上面一行的单元格来做到这一点,但是似乎选择一个跨越多列的单元格只有在选择它最左边的索引时才有效。在我的示例中,选择 index(1,1) 或 index(0,2) 什么都不做。所以我需要能够在给定单元格跨越的任何索引的情况下选择一个单元格。我怎样才能做到这一点?例如给定索引(0,2)或索引(0,3),它们都是列跨度为4的相同单元格,我如何以编程方式确定该单元格从索引(0,0)开始

【问题讨论】:

    标签: python pyqt pyqt5 selection qtableview


    【解决方案1】:

    您必须在QAbstractItemView::MultiSelection 中将其设置为选择模式,并且要选择它,您必须使用setSelection(),将属于QModelIndex 的矩形传递给它:

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            self._model = QtGui.QStandardItemModel(3, 8)
            self._table = QtWidgets.QTableView(
                selectionMode=QtWidgets.QAbstractItemView.MultiSelection,
                clicked=self.on_clicked,
            )
            self._table.setModel(self._model)
            self.fill_table()
            self.setCentralWidget(self._table)
    
        def fill_table(self):
            data = [
                ('A', (0, 0), (1, 4)),
                ('B', (0, 4), (1, 4)),
                ('one', (1, 0), (1, 2)),
                ('two', (1, 2), (1, 2)),
                ('three', (1, 4), (1, 2)),
                ('four', (1, 6), (1, 2)),
                ('x', (2, 0), (1, 1)),
                ('y', (2, 1), (1, 1)),
                ('x', (2, 2), (1, 1)),
                ('y', (2, 3), (1, 1)),
                ('x', (2, 4), (1, 1)),
                ('y', (2, 5), (1, 1)),
                ('x', (2, 6), (1, 1)),
                ('y', (2, 7), (1, 1)),
            ]
            for text, (r, c), (rs, cs) in data:
                it = QtGui.QStandardItem(text)
                self._model.setItem(r, c, it)
                self._table.setSpan(r, c, rs, cs)
    
        @QtCore.pyqtSlot('QModelIndex')
        def on_clicked(self, ix):
            self._table.clearSelection()
            row, column = ix.row(), ix.column()
            sm = self._table.selectionModel()
            indexes = [ix]
            for i in range(row):
                ix = self._model.index(i, column)
                indexes.append(ix)
            for ix in indexes:
                r = self._table.visualRect(ix)
                self._table.setSelection(r, QtCore.QItemSelectionModel.Select)
    
    
    if __name__ == '__main__':
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        w = MainWindow()
        w.show()
        sys.exit(app.exec_())
    

    【讨论】:

    • 啊让 visualRect(ix) 使用 setSelection 中的索引是我想不到的。谢谢!
    猜你喜欢
    • 2017-09-28
    • 2018-10-23
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 2011-10-16
    • 2015-12-29
    • 2014-02-12
    • 1970-01-01
    相关资源
    最近更新 更多