主頁 > 區塊鏈 > Qt-每次呼叫QSortFilterProxyModel::invalidateFilter時都會重置rootIndex

Qt-每次呼叫QSortFilterProxyModel::invalidateFilter時都會重置rootIndex

2021-11-29 03:09:01 區塊鏈

我需要一個QTabWidget每個選項卡都包含一個QTreeView. 每個都QTreeView顯示一個更大模型的“分支”。用戶QLineEdit可以根據他們輸入內容實時過濾視圖。我復制了下面的 GUI 問題。

問題是我使用QTreeView::setRootIndex它來顯示主模型的單個內部分支。QLineEdit“filterer”與實作 QSortFilterProxyModel每當用戶鍵入時,我都會呼叫 QSortFilterProxyModel::invalidateFilter從頭開始重新過濾。這兩種方法QTreeView::setRootIndexQSortFilterProxyModel::invalidateFilter不能很好地混合在一起。

QSortFilterProxyModel::invalidateFilter被呼叫時,我之前設定的索引QTreeView::setRootIndex現在無效。QTreeView隨后顯示了整個樹,而不是“分支”,我一直在使用之前選擇的setRootIndexQTreeView有效地“忘記”根指數我已成立。

我復制了下面的問題

import functools

from Qt import QtCore, QtWidgets

_NO_ROW = -1
_NUMBER_OF_BRANCHES = 3


class _MatchProxy(QtCore.QSortFilterProxyModel):
    """Use a callable function to determine if an index should be hidden from view or not."""

    def __init__(self, matcher, parent=None):
        super(_MatchProxy, self).__init__(parent=parent)

        self._matcher = matcher

    def filterAcceptsRow(self, source_row, source_index):
        return self._matcher(source_index)


class _MultiTree(QtWidgets.QWidget):
    """A widget which makes smaller, individual QTreeViews for each section of an given index."""

    def __init__(self, source_index, parent=None):
        super(_MultiTree, self).__init__(parent=parent)

        self.setLayout(QtWidgets.QVBoxLayout())

        model = source_index.model()

        self._views = []

        for index in range(model.rowCount(source_index)):
            section = model.index(index, 0, parent=source_index)
            label = model.data(section, QtCore.Qt.DisplayRole)
            view = QtWidgets.QTreeView()
            view.setModel(model)
            view.setRootIndex(section)

            self.layout().addWidget(QtWidgets.QLabel(label))
            self.layout().addWidget(view)

            self._views.append(view)

    def iter_models(self):
        for view in self._views:
            yield view.model()

    def iter_views(self):
        for view in self._views:
            yield view


class Node(object):
    """A generic name   children   parent graph node class."""

    def __init__(self, name, parent=None):
        super(Node, self).__init__()

        self._name = name
        self._children = []
        self._parent = parent

        if self._parent:
            self._parent.add_child(self)

    def add_child(self, node):
        node._parent = self
        self._children.append(node)

    def get_child(self, row):
        return self._children[row]

    def get_children(self):
        return list(self._children)

    def get_label(self):
        return self._name

    def get_parent(self):
        return self._parent

    def get_row(self):
        parent = self.get_parent()

        if not parent:
            return _NO_ROW

        return parent.get_children().index(self)

    def __repr__(self):
        return "{self.__class__.__name__}({self._name!r}, parent={self._parent!r})".format(
            self=self
        )


class Branch(Node):
    """Syntax sugar for debugging. This class isn't "necessary" for the reproduction."""

    pass


class Model(QtCore.QAbstractItemModel):
    """The basic Qt model which contains the entire tree, including each branch."""

    def __init__(self, roots, parent=None):
        super(Model, self).__init__(parent=parent)

        self._roots = roots

    def _get_node(self, index):
        return index.internalPointer()

    def columnCount(self, _):
        return 1

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return None

        node = self._get_node(index)

        return node.get_label()

    def index(self, row, column, parent=QtCore.QModelIndex()):
        if not parent.isValid():
            return self.createIndex(row, 0, self._roots[row])

        parent_node = self._get_node(parent)
        child_node = parent_node.get_child(row)

        return self.createIndex(row, column, child_node)

    def parent(self, index):
        if not index.isValid():
            return QtCore.QModelIndex()

        node = self._get_node(index)
        parent = node.get_parent()

        if not parent:
            return QtCore.QModelIndex()

        return self.createIndex(node.get_row(), 0, parent)

    def rowCount(self, index):
        if not index.isValid():
            return len(self._roots)

        node = self._get_node(index)

        return len(node.get_children())


class Widget(QtWidgets.QWidget):
    """The main widget / window which has the filterer   QTreeViews."""

    def __init__(self, model, parent=None):
        super(Widget, self).__init__(parent=parent)

        self.setLayout(QtWidgets.QVBoxLayout())

        self._filterer = QtWidgets.QLineEdit()
        self._tabs = QtWidgets.QTabWidget()

        self._set_model(model)

        self.layout().addWidget(self._filterer)
        self.layout().addWidget(self._tabs)

        self._filterer.textChanged.connect(self._update_current_view)

    def _replace_model_with_filterer_proxy(self, view):
        def _match(line_edit, index):
            if not index.isValid():
                return True  # Show everything, don't filter anything

            current = line_edit.text().strip()

            if not current:
                return True  # Show everything, don't filter anything.

            return current in index.data(QtCore.Qt.DisplayRole)

        model = view.model()
        current_root = view.rootIndex()
        proxy = _MatchProxy(functools.partial(_match, self._filterer))
        proxy.setSourceModel(model)
        proxy.setRecursiveFilteringEnabled(True)
        view.setModel(proxy)
        view.setRootIndex(proxy.mapFromSource(current_root))

    def _set_model(self, model):
        tabs_count = model.rowCount(QtCore.QModelIndex())

        for row in range(tabs_count):
            branch_index = model.index(row, 0)
            tab_name = model.data(branch_index, QtCore.Qt.DisplayRole)
            widget = _MultiTree(branch_index)

            for view in widget.iter_views():
                self._replace_model_with_filterer_proxy(view)

            self._tabs.addTab(widget, tab_name)

    def _update_current_view(self):
        widget = self._tabs.currentWidget()

        for proxy in widget.iter_models():
            proxy.invalidateFilter()


def _make_branch_graph():
    default = Node("default")
    optional = Node("optional")

    Node("camera", parent=default)
    Node("set", parent=default)
    light = Node("light", parent=default)
    Node("directional light", parent=light)
    spot = Node("spot light", parent=light)
    Node("light center", parent=spot)
    Node("volume light", parent=light)

    Node("model", parent=optional)
    surfacing = Node("surfacing", parent=optional)
    Node("look", parent=surfacing)
    Node("hair", parent=surfacing)
    Node("fur", parent=surfacing)
    Node("rig", parent=optional)

    return (default, optional)


def _make_full_graph():
    roots = []

    for index in range(_NUMBER_OF_BRANCHES):
        branch = Branch("branch_{index}".format(index=index))

        for node in _make_branch_graph():
            branch.add_child(node)

        roots.append(branch)

    return roots


def main():
    application = QtWidgets.QApplication([])

    roots = _make_full_graph()
    model = Model(roots)
    window = Widget(model)
    window.show()

    application.exec_()


if __name__ == "__main__":
    main()
  • 運行上面的代碼以打開 GUI。選項卡 內部 QTreeViews 應如下所示:
QTabWidget tab - branch_0
    QTreeView (default)
        - camera
        - set
        - light
            - directional light
            - spot light
                - light center
            - volume light
    QTreeView (optional)
        - model
        - surfacing
            - look
            - hair
            - fur
        - rig
QTabWidget tab - branch_1
    - Same as branch_0
QTabWidget tab - branch_2
    - Same as branch_0

這是正確的、預期的節點顯示。現在在過濾器 QLineEdit 中,輸入“light”。您現在將獲得:

QTabWidget tab - branch_0
    QTreeView (default)
        - light
            - directional light
            - spot light
                - light center
            - volume light
    QTreeView (optional)
        - branch_0
            - default
                - light
                    - directional light
                    - spot light
                        - light center
                    - volume light
        - branch_1
            - default
                - light
                    - directional light
                    - spot light
                        - light center
                    - volume light
        - branch_2
            - default
                - light
                    - directional light
                    - spot light
                        - light center
                    - volume light
QTabWidget tab - branch_1
    - Same as branch_0
QTabWidget tab - branch_2
    - Same as branch_0

在這里您可以看到標記為“可選”的 QTreeView 現在顯示每個分支的內容,而不是像它應該的那樣只顯示一個分支。

這不是預期的行為。作為參考,這是我希望得到的觀點:

QTabWidget tab - branch_0
    QTreeView (default)
        - default
            - light
                - directional light
                - spot light
                    - light center
                - volume light
    QTreeView (optional) [EMPTY, no children]
QTabWidget tab - branch_1
    - Same as branch_0
QTabWidget tab - branch_2
    - Same as branch_0

Also notice that if you clear the filterer QLineEdit's text, "", you don't go back to the first graph. The "optional" QTreeView is stuck being shown everything, in every QTreeView.

Now in the filterer QLineEdit text, type "asdf". Now the graph is

QTabWidget tab - branch_0
    QTreeView (default)
        - branch_0
        - branch_1
        - branch_2
    QTreeView (optional)
        - branch_0
        - branch_1
        - branch_2
QTabWidget tab - branch_1
    - Same as branch_0
QTabWidget tab - branch_2
    - Same as branch_0

When my intended view was

QTabWidget tab - branch_0
    QTreeView (default) [EMPTY]
    QTreeView (optional) [EMPTY]
QTabWidget tab - branch_1
    - Same as branch_0
QTabWidget tab - branch_2
    - Same as branch_0

And if you clear the filterer text with "", now both QTreeViews show everything across all branches.

Is there a simple way to get the intended graph that I'm describing? Maybe there's a way to re-run QSortFilterProxyModel without invalidating indices, or some other mechanism I can use to get the same effect? At the moment I'm getting around the problem by "saving and restoring" the rootIndex for each view, pre and post invalidateFilter. But my approach for that doesn't work in all cases and feels like a hack.

對此的任何建議將不勝感激。

uj5u.com熱心網友回復:

問題來自這樣一個事實,即在應用過濾時,未被接受的索引成為無效索引,而對于 Qt 而言,無效索引與索引相同
由于您將視圖的根索引設定為過濾器使無效的索引,因此結果與 do 相同setRootIndex(QModelIndex()),它顯示了整個模型。

事實上,如果您嘗試使用不匹配任何“默認”分支項的字串過濾模型,也會遇到您在“可選”視圖中看到的相同問題:它將顯示整個根樹模型,這是因為如果索引無效,您的_match函式將回傳True,因此無論如何都會顯示根(在正常情況下,它會顯示一個空模型)。
請注意這方面:我不確定所需的行為,但如果過濾器不匹配任何內容,則不應回傳True,因為這將使所有根索引都有效,在您的情況下,即使它不應該是顯示的索引。

問題的根源在于模型不知道視圖的根索引(也不應該知道!)并且視圖無法知道無效的根索引何時再次變為有效(再次,它也不應該知道) )。請參閱有關類似問題的討論

一個可能的解決方案(它沒有解決接受無效根的問題)是跟蹤根索引,然后通過連接到模型的信號來更新視圖rowsRemoved,最重要的是,rowsInserted這樣我們就可以恢復原始的每當根索引再次“可用”時:

class TreePersistentRootIndex(QtWidgets.QTreeView):
    _sourceRootIndex = QtCore.QModelIndex()
    def setModel(self, model):
        if self.model() and isinstance(self.model(), QtCore.QSortFilterProxyModel):
            self.model().layoutChanged.disconnect(self.checkRootIndex)
            self.model().rowsRemoved.disconnect(self.checkRootIndex)
            self.model().rowsInserted.disconnect(self.checkRootIndex)
        super().setModel(model)
        self._model = model
        if isinstance(model, QtCore.QSortFilterProxyModel):
            model.layoutChanged.connect(self.checkRootIndex)
            model.rowsRemoved.connect(self.checkRootIndex)
            model.rowsInserted.connect(self.checkRootIndex)

    def checkRootIndex(self):
        if (not self._sourceRootIndex.isValid() or 
            not isinstance(self.model(), QtCore.QSortFilterProxyModel)):
                return
        rootIndex = self.model().mapFromSource(self._sourceRootIndex)
        if rootIndex != self.rootIndex():
            super().setRootIndex(rootIndex)

    def setRootIndex(self, rootIndex):
        super().setRootIndex(rootIndex)
        if isinstance(self.model(), QtCore.QSortFilterProxyModel):
            rootIndex = self.model().mapToSource(rootIndex)
        self._sourceRootIndex = rootIndex


class _MultiTree(QtWidgets.QWidget):
    def __init__(self, source_index, parent=None):
        # ...
        for index in range(model.rowCount(source_index)):
            section = model.index(index, 0, parent=source_index)
            label = model.data(section, QtCore.Qt.DisplayRole)
            view = TreePersistentRootIndex()
            # ...

為了克服接受的根索引的問題,您可能會考慮更改過濾行為,或者最終(如果您完全確定如果過濾器不匹配任何子項,則不應在子根索引中顯示任何內容)中,使用setRowHidden()利用True(如在隱藏)如果所得的索引無效或False(如在顯示),否則。

可能的實作(未完全測驗)可能如下:

    def checkRootIndex(self):
        # ...as above, then:
        if rootIndex.isValid() != self._sourceRootIndex.isValid():
            hide = not rootIndex.isValid()
            for row in range(self.model().rowCount(rootIndex)):
                self.setRowHidden(row, rootIndex.parent(), hide)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/368570.html

標籤:Python qt 模型视图控制器 pyqt pyside

上一篇:如何將.csv檔案與我的Qt應用程式的發布版本鏈接?

下一篇:QWebEngineView不會加載本地檔案,但會完美加載遠程網頁

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • JAVA使用 web3j 進行token轉賬

    最近新學習了下區塊鏈這方面的知識,所學不多,給大家分享下。 # 1. 關于web3j web3j是一個高度模塊化,反應性,型別安全的Java和Android庫,用于與智能合約配合并與以太坊網路上的客戶端(節點)集成。 # 2. 準備作業 jdk版本1.8 引入maven <dependency> < ......

    uj5u.com 2020-09-10 03:03:06 more
  • 以太坊智能合約開發框架Truffle

    前言 部署智能合約有多種方式,命令列的瀏覽器的渠道都有,但往往跟我們程式員的風格不太相符,因為我們習慣了在IDE里寫了代碼然后打包運行看效果。 雖然現在IDE中已經存在了Solidity插件,可以撰寫智能合約,但是部署智能合約卻要另走他路,沒辦法進行一個快捷的部署與測驗。 如果團隊管理的區塊節點多、 ......

    uj5u.com 2020-09-10 03:03:12 more
  • 谷歌二次驗證碼成為區塊鏈專用安全碼,你怎么看?

    前言 谷歌身份驗證器,前些年大家都比較陌生,但隨著國內互聯網安全的加強,它越來越多地出現在大家的視野中。 比較廣泛接觸的人群是國際3A游戲愛好者,游戲盜號現象嚴重+國外賬號安全應用廣泛,這類游戲一般都會要求用戶系結名為“兩步驗證”、“雙重驗證”等,平臺一般都推薦用谷歌身份驗證器。 后來區塊鏈業務風靡 ......

    uj5u.com 2020-09-10 03:03:17 more
  • 密碼學DAY1

    目錄 ##1.1 密碼學基本概念 密碼在我們的生活中有著重要的作用,那么密碼究竟來自何方,為何會產生呢? 密碼學是網路安全、資訊安全、區塊鏈等產品的基礎,常見的非對稱加密、對稱加密、散列函式等,都屬于密碼學范疇。 密碼學有數千年的歷史,從最開始的替換法到如今的非對稱加密演算法,經歷了古典密碼學,近代密 ......

    uj5u.com 2020-09-10 03:03:50 more
  • 密碼學DAY1_02

    目錄 ##1.1 ASCII編碼 ASCII(American Standard Code for Information Interchange,美國資訊交換標準代碼)是基于拉丁字母的一套電腦編碼系統,主要用于顯示現代英語和其他西歐語言。它是現今最通用的單位元組編碼系統,并等同于國際標準ISO/IE ......

    uj5u.com 2020-09-10 03:04:50 more
  • 密碼學DAY2

    ##1.1 加密模式 加密模式:https://docs.oracle.com/javase/8/docs/api/javax/crypto/Cipher.html ECB ECB : Electronic codebook, 電子密碼本. 需要加密的訊息按照塊密碼的塊大小被分為數個塊,并對每個塊進 ......

    uj5u.com 2020-09-10 03:05:42 more
  • NTP時鐘服務器的特點(京準電子)

    NTP時鐘服務器的特點(京準電子) NTP時鐘服務器的特點(京準電子) 京準電子官V——ahjzsz 首先對時間同步進行了背景介紹,然后討論了不同的時間同步網路技術,最后指出了建立全球或區域時間同步網存在的問題。 一、概 述 在通信領域,“同步”概念是指頻率的同步,即網路各個節點的時鐘頻率和相位同步 ......

    uj5u.com 2020-09-10 03:05:47 more
  • 標準化考場時鐘同步系統推進智能化校園建設

    標準化考場時鐘同步系統推進智能化校園建設 標準化考場時鐘同步系統推進智能化校園建設 安徽京準電子科技官微——ahjzsz 一、背景概述隨著教育事業的快速發展,學校建設如雨后春筍,隨之而來的學校教育、管理、安全方面的問題成了學校管理人員面臨的最大的挑戰,這些問題同時也是學生家長所擔心的。為了讓學生有更 ......

    uj5u.com 2020-09-10 03:05:51 more
  • 位元幣入門

    引言 位元幣基本結構 位元幣基礎知識 1)哈希演算法 2)非對稱加密技術 3)數字簽名 4)MerkleTree 5)哪有位元幣,有的是UTXO 6)位元幣挖礦與共識 7)區塊驗證(共識) 總結 引言 上一篇我們已經知道了什么是區塊鏈,此篇說一下區塊鏈的第一個應用——位元幣。其實先有位元幣,后有的區塊 ......

    uj5u.com 2020-09-10 03:06:15 more
  • 北斗對時服務器(北斗對時設備)電力系統應用

    北斗對時服務器(北斗對時設備)電力系統應用 北斗對時服務器(北斗對時設備)電力系統應用 京準電子科技官微(ahjzsz) 中國北斗衛星導航系統(英文名稱:BeiDou Navigation Satellite System,簡稱BDS),因為是目前世界范圍內唯一可以大面積提供免費定位服務的系統,所以 ......

    uj5u.com 2020-09-10 03:06:20 more
最新发布
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:46:47 more
  • Hyperledger Fabric 使用 CouchDB 和復雜智能合約開發

    在上個實驗中,我們已經實作了簡單智能合約實作及客戶端開發,但該實驗中智能合約只有基礎的增刪改查功能,且其中的資料管理功能與傳統 MySQL 比相差甚遠。本文將在前面實驗的基礎上,將 Hyperledger Fabric 的默認資料庫支持 LevelDB 改為 CouchDB 模式,以實作更復雜的資料... ......

    uj5u.com 2023-04-16 07:28:31 more
  • .NET Core 波場鏈離線簽名、廣播交易(發送 TRX和USDT)筆記

    Get Started NuGet You can run the following command to install the Tron.Wallet.Net in your project. PM> Install-Package Tron.Wallet.Net 配置 public reco ......

    uj5u.com 2023-04-14 08:08:00 more
  • DKP 黑客分析——不正確的代幣對比率計算

    概述: 2023 年 2 月 8 日,針對 DKP 協議的閃電貸攻擊導致該協議的用戶損失了 8 萬美元,因為 execute() 函式取決于 USDT-DKP 對中兩種代幣的余額比率。 智能合約黑客概述: 攻擊者的交易:0x0c850f,0x2d31 攻擊者地址:0xF38 利用合同:0xf34ad ......

    uj5u.com 2023-04-07 07:46:09 more
  • Defi開發簡介

    Defi開發簡介 介紹 Defi是去中心化金融的縮寫, 是一項旨在利用區塊鏈技術和智能合約創建更加開放,可訪問和透明的金融體系的運動. 這與傳統金融形成鮮明對比,傳統金融通常由少數大型銀行和金融機構控制 在Defi的世界里,用戶可以直接從他們的電腦或移動設備上訪問廣泛的金融服務,而不需要像銀行或者信 ......

    uj5u.com 2023-04-05 08:01:34 more
  • solidity簡單的ERC20代幣實作

    // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "hardhat/console.sol"; //ERC20 同質化代幣,每個代幣的本質或性質都是相同 //ETH 是原生代幣,它不是ERC20代幣, ......

    uj5u.com 2023-03-21 07:56:29 more
  • solidity 參考型別修飾符memory、calldata與storage 常量修飾符C

    在solidity語言中 參考型別修飾符(參考型別為存盤空間不固定的數值型別) memory、calldata與storage,它們只能修飾參考型別變數,比如字串、陣列、位元組等... memory 適用于方法傳參、返參或在方法體內使用,使用完就會清除掉,釋放記憶體 calldata 僅適用于方法傳參 ......

    uj5u.com 2023-03-08 07:57:54 more
  • solidity注解標簽

    在solidity語言中 注釋符為// 注解符為/* 內容*/ 或者 是 ///內容 注解中含有這幾個標簽給予我們使用 @title 一個應該描述合約/介面的標題 contract, library, interface @author 作者的名字 contract, library, interf ......

    uj5u.com 2023-03-08 07:57:49 more
  • 評價指標:相似度、GAS消耗

    【代碼注釋自動生成方法綜述】 這些評測指標主要來自機器翻譯和文本總結等研究領域,可以評估候選文本(即基于代碼注釋自動方法而生成)和參考文本(即基于手工方式而生成)的相似度. BLEU指標^[^?88^^?^]^:其全稱是bilingual evaluation understudy.該指標是最早用于 ......

    uj5u.com 2023-02-23 07:27:39 more
  • 基于NOSTR協議的“公有制”版本的Twitter,去中心化社交軟體Damus

    最近,一個幽靈,Web3的幽靈,在網路游蕩,它叫Damus,這玩意詮釋了什么叫做病毒式營銷,滑稽的是,一個Web3產品卻在Web2的產品鏈上瘋狂傳銷,各方大佬紛紛為其背書,到底發生了什么?Damus的葫蘆里,賣的是什么藥? 注冊和簡單實用 很少有什么產品在用戶注冊環節會有什么噱頭,但Damus確實出 ......

    uj5u.com 2023-02-05 06:48:39 more