首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QSortFilterProxyModel隐藏QWidget

QSortFilterProxyModel隐藏QWidget
EN

Stack Overflow用户
提问于 2020-11-21 05:51:43
回答 1查看 136关注 0票数 0

我有一个容纳数据的QStandardItemModel。在其中一个专栏中,我想添加一些QWidgets (可点击的图片)。但是,在添加QSortFilterProxyModel以进行排序/过滤之后,QSortFilterProxyModel隐藏了我想要的QWidget

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

一个最小的例子,使用QPushButton作为我想要的QWidget

代码语言:javascript
复制
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_()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-21 12:09:35

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

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

代码语言:javascript
复制
tab.setIndexWidget(proxy.index(0, 0), QPushButton("hi"))

或者,更好的:

代码语言:javascript
复制
tab.setIndexWidget(tab.model().index(0, 0), QPushButton("hi"))

请注意,这显然意味着,每当由于筛选或排序而更改模型时,您可能会遇到一些不一致的情况,这也是索引小部件仅用于静态和简单模型的另一个原因,而委托则是首选解决方案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64940276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档