I found code for finding child widget <Top-widget.findChildren(widget-type)>, but I couldn't able to find command for getting parent widget.
I created QTabWidget with multiple tabs . in each tabs I have some widgets. I want to highlight tab page of given widget element.
I created one code to achieve this. and it is working. but I feels this is not straight forward. can you suggest better solution to achieve the same?
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()
CodePudding user response:
You can use isAncestorOf
, which returns True
if the widget in the argument is a child (or grandchild, at any level):
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