我有一个容纳数据的QStandardItemModel。在其中一个专栏中,我想添加一些QWidgets (可点击的图片)。但是,在添加QSortFilterProxyModel以进行排序/过滤之后,QSortFilterProxyModel隐藏了我想要的QWidget。
我在互联网上搜索过,但是找不到如何同时保存QWidget和QSortFilterProxyModel。如果有人能在这个问题上指导我,我将不胜感激。谢谢。
一个最小的例子,使用QPushButton作为我想要的QWidget
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_()发布于 2020-11-21 12:09:35
使用seyIndexWidget添加的小部件被添加到视图中,而不是添加到模型中。传递给函数的索引只是视图用来知道这些小部件将放在哪里的引用,而该引用必须是视图中使用的实际模型的引用。
如果在视图中使用代理模型,则必须给出代理的索引,而不是源的索引。
tab.setIndexWidget(proxy.index(0, 0), QPushButton("hi"))或者,更好的:
tab.setIndexWidget(tab.model().index(0, 0), QPushButton("hi"))请注意,这显然意味着,每当由于筛选或排序而更改模型时,您可能会遇到一些不一致的情况,这也是索引小部件仅用于静态和简单模型的另一个原因,而委托则是首选解决方案。
https://stackoverflow.com/questions/64940276
复制相似问题