簡體   English   中英

如何在 pyqt5 中找到小部件的父 TabPage?

[英]how to find parent TabPage of widget in pyqt5?

我找到了查找子小部件 <Top-widget.findChildren(widget-type)> 的代碼,但我無法找到獲取父小部件的命令。

我創建了帶有多個選項卡的 QTabWidget。 在每個選項卡中,我都有一些小部件。 我想突出顯示給定小部件元素的標簽頁。

我創建了一個代碼來實現這一點。 它正在工作。 但我覺得這不是直截了當的。 你能提出更好的解決方案來實現同樣的目標嗎?

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

def color_parent_tab(widget,Tab):
    tabs={Tab.widget(i):i for i in range(Tab.count())}
    while widget!=None:
        try:
            if widget in tabs:
                Tab.tabBar().setTabTextColor(tabs[widget], QColor('red'))
            widget=widget.parent()
        except Exception as e:print(e)


if __name__ == '__main__':
    app = QApplication([])
    window=QTabWidget()

    w=QWidget()
    VL=QVBoxLayout(w)
    window.addTab(w,'tab1')

    L=QLabel('Label1')
    VL.addWidget(L)

    L2=QLabel('Label2')
    VL.addWidget(L2)

    w=QWidget()
    VL=QVBoxLayout(w)
    window.addTab(w,'tab2')

    L3=QLabel('Label1')
    VL.addWidget(L3)

    L4=QLineEdit()
    VL.addWidget(L4)

    color_parent_tab(L3,window)

    window.showMaximized()
    app.exec()

您可以使用isAncestorOf ,如果參數中的小部件是孩子(或孫,在任何級別),則返回True

def color_parent_tab(widget, Tab):
    for i in range(Tab.count()):
        if Tab.widget(i).isAncestorOf(widget):
            Tab.tabBar().setTabTextColor(i, QColor('red'))
            return

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM