Python QSortFilterProxyModel隐藏QWidget

Python QSortFilterProxyModel隐藏QWidget,python,pyqt5,qsortfilterproxymodel,Python,Pyqt5,Qsortfilterproxymodel,我有一个容纳数据的QStandardItemModel。在其中一列中,我想添加一些QWidgets(可点击图片)。但是,在添加用于排序/筛选的QSortFilterProxyModel后,QSortFilterProxyModel会隐藏所需的QWidgets 我在互联网上搜索过,但找不到如何同时保存QWidget和QSortFilterProxyModel。如果有人能在这个问题上指导我,我将不胜感激。谢谢 一个最简单的示例,按照我的要求使用QPushButton: from PyQt5.QtWi

我有一个容纳数据的
QStandardItemModel
。在其中一列中,我想添加一些
QWidget
s(可点击图片)。但是,在添加用于排序/筛选的
QSortFilterProxyModel
后,
QSortFilterProxyModel
会隐藏所需的
QWidget
s

我在互联网上搜索过,但找不到如何同时保存
QWidget
QSortFilterProxyModel
。如果有人能在这个问题上指导我,我将不胜感激。谢谢

一个最简单的示例,按照我的要求使用
QPushButton

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Buttons(QWidget):
    def __init__(self):
        super().__init__()
        layout = QHBoxLayout(self)
        layout.addWidget(QPushButton('btn1'))
        layout.addWidget(QPushButton('btn2'))
        self.setLayout(layout)

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        tab = QTableView()
        sti = QStandardItemModel()
        if True:    # This shows the buttons in a cell
            tab.setModel(sti)
        else:       # This does not show the buttons
            proxy = QSortFilterProxyModel()
            proxy.setSourceModel(sti)
            tab.setModel(proxy)
        sti.appendRow([QStandardItem(str(i)) for i in range(5)])
        tab.setIndexWidget(sti.index(0, 0), QPushButton("hi"))
        sti.appendRow([])
        tab.setIndexWidget(sti.index(1, 2), Buttons())
        self.setCentralWidget(tab)

app = QApplication([])
window = MainWindow()
window.resize(800, 600)
window.show()
app.exec_()

使用
seyIndexWidget
添加的小部件将添加到视图中,而不是添加到模型中。传递给函数的索引只是视图用来知道这些小部件将放置在何处的引用,该引用必须是视图中使用的实际模型的引用

如果在视图中使用代理模型,则必须给出代理的索引,而不是源的索引

tab.setIndexWidget(proxy.index(0, 0), QPushButton("hi"))
或者更好:

tab.setIndexWidget(tab.model().index(0, 0), QPushButton("hi"))
请注意,这显然意味着,无论何时由于过滤或排序而更改模型,您都可能会遇到一些不一致的情况,这也是索引小部件应仅用于静态和简单模型的另一个原因,委托是首选解决方案