我试图对照QMenu中的项目列表检查QTabBar中的现有选项卡。并且,如果现有标签页包含在QMenu中找不到的项目,则该标签页将以红色突出显示。
最初,我使用的是tabTextColor
,但是它似乎并没有改变文本的颜色。
然后,当我在Google上四处搜寻时,有人说要使用setStylesheet
来代替,因此我决定更改背景颜色,而不是最初要使用的文本颜色。
即使如此,我在“保留”红色/将颜色设置为特定标签时仍然遇到问题。 在我的以下代码中,如果执行以下操作:
add
按钮,这会将B选项卡突出显示为红色感谢对此有任何见识。
class MyWin(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MyWin, self).__init__()
central_widget = QtGui.QWidget()
self.setCentralWidget(central_widget)
vlay = QtGui.QVBoxLayout(central_widget)
hlay = QtGui.QHBoxLayout()
vlay.addLayout(hlay)
vlay.addStretch()
self.add_button = QtGui.QToolButton()
self.tab_bar = QtGui.QTabBar(self)
self.add_button.setIcon(QtGui.QIcon('add.png'))
self.qmenu = QtGui.QMenu(self.add_button)
self.add_button.setMenu(self.qmenu)
self.add_button.setPopupMode(QtGui.QToolButton.InstantPopup)
self.qmenu.aboutToShow.connect(self.set_menu)
self.tab_bar.setTabButton(
0,
QtGui.QTabBar.ButtonPosition.RightSide,
self.add_button
)
hlay.addWidget(self.add_button)
hlay.addWidget(self.tab_bar)
@QtCore.pyqt.Slot()
def set_menu(self):
with open('/Desktop/item_file.txt') as f:
menu_options = f.read().splitlines()
self.qmenu.clear()
self.tabs_precheck()
for opt in menu_options:
self.qmenu.addAction(opt, partial(self.set_new_tab, opt))
def get_all_tabs(self):
all_existing_tabs = {}
for index in range(self.tab_bar.count()):
all_existing_tabs[index] = self.tab_bar.tabText(index)
return all_existing_tabs
def set_new_tab(self, opt):
all_tabs = self.get_all_tabs()
if not opt in all_tabs.values():
self.tab_bar.addTab(opt)
def tabs_precheck(self):
# Get the tabs that are already populated
before_tabs = {}
for index in range(self.tab_bar.count()):
before_tabs[self.tab_bar.tabText(index)] = index
# Get the items in qmenu items
with open('/Desktop/item_file.txt') as f:
qmenu_items = f.read().splitlines()
# Get the difference between the 2
difference = list(set(before_tabs.keys()) - set(qmenu_items))
for diff in difference:
# Get the 'before' index
index_value = before_tabs.get(diff)
# Set that particular tab background color to 'RED'
self.tab_bar.setCurentIndex(index_value)
self.tab_bar.setStyleSheet('''
QTabBar::tab {background-color: red;}
'''
)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = MyWin()
w.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
您必须使用setTabTextColor()
,但我发现它失败了,因为您应用了错误的逻辑,解决方法是:
def tabs_precheck(self):
with open('/Desktop/item_file.txt') as f:
qmenu_items = f.read().splitlines()
if qmenu_items:
for index in range(self.tab_bar.count()):
text = self.tab_bar.tabText(index)
color = QtCore.Qt.black if text in qmenu_items else QtCore.Qt.red
self.tab_bar.setTabTextColor(index, color)