我正在尝试根据QTabBar中的项目列表检查QMenu中的现有选项卡。如果现有的选项卡包含在QMenu中找不到的项,则该选项卡将以红色高亮显示。
最初我使用的是tabTextColor,但是它似乎并没有改变文本的颜色。然后,当我在谷歌上搜索时,有些人说要使用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_())发布于 2019-01-07 22:50:48
您必须使用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)https://stackoverflow.com/questions/54081476
复制相似问题