我有一个容纳数据的QStandardItemModel
。在其中一个专栏中,我想添加一些QWidget
(可点击图片)。但是,在为排序/筛选目的添加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_()
使用
seyIndexWidget
添加的小部件将添加到视图,而不是模型。传递给函数的索引只是视图用于知道这些小部件将放置在何处的引用,该引用必须是视图中使用的实际模型的引用如果在视图中使用代理模型,则必须给出代理的索引,而不是源的索引
或者更好:
请注意,这显然意味着,无论何时由于过滤或排序而更改模型,您都可能会遇到一些不一致的情况,这也是索引小部件应仅用于静态和简单模型的另一个原因,委托是首选解决方案
相关问题 更多 >
编程相关推荐