繁体   English   中英

如何在 PyQt5 中设置所选 QComboBox 元素的样式?

[英]How do I set the style of the selected QComboBox element in PyQt5?

如何为所选元素添加一些样式(在本例中为 1)?

例如,如何将被选元素的背景涂成红色?

这是代码

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow
import sys


class Ui_MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.comboBox = QtWidgets.QComboBox(self)
        self.comboBox.addItem("1")
        self.comboBox.addItem("2")
        self.comboBox.addItem("3")
        self.comboBox.setStyleSheet('''''')



if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = Ui_MainWindow()
    MainWindow.show()
    sys.exit(app.exec_())

例如,我有相同的代码,但我使用 QWidgets exept QComboBox

from PyQt5 import QtWidgets, QtCore, QtGui


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.centralwidget = QtWidgets.QWidget()
        self.centralwidget.setObjectName("centralwidget")
        self.setCentralWidget(self.centralwidget)

        mainMenu = self.menuBar()
        mainMenu.setNativeMenuBar(False)
        self.fileMenu = mainMenu.addMenu('Menu')

        action1 = QtWidgets.QWidgetAction(self, objectName="action1")
        self.label1 = QtWidgets.QLabel("Action 1", objectName="label1")
        action1.setDefaultWidget(self.label1);
        action1.setText('Action 1')

        action2 = QtWidgets.QWidgetAction(self, objectName="action2")
        self.label2 = QtWidgets.QLabel("Action 2", objectName="label2")
        action2.setDefaultWidget(self.label2);
        action2.setText('Action 2')

        action3 = QtWidgets.QWidgetAction(self, objectName="action3")
        self.label3 = QtWidgets.QLabel("Action 3", objectName="label3")
        action3.setDefaultWidget(self.label3);
        action3.setText('Action 3')

        self.fileMenu.addAction(action1)
        self.fileMenu.addAction(action2)
        self.fileMenu.addAction(action3)
        self.fileMenu.triggered.connect(self.triggered_action)

        layout = QtWidgets.QHBoxLayout(self.centralwidget)
        layout.addWidget(mainMenu)

        self.triggered_action(action1)

    def triggered_action(self, q):
        objectName = q.objectName()

        self.label1.setStyleSheet("""
            QLabel {background-color: #ABABAB; padding: 10px 12px 10px 12px;}
            QLabel:hover {background-color: #654321;}
        """)
        self.label2.setStyleSheet("""
            QLabel {background-color: #ABABAB; padding: 10px 12px 10px 12px;}
            QLabel:hover{background-color: #654321;}
        """)
        self.label3.setStyleSheet("""
            QLabel {background-color: #ABABAB; padding: 10px 12px 10px 12px;}
            QLabel:hover {background-color: #654321;}
        """)

        if objectName == 'action1':
            self.label1.setStyleSheet("""
                QLabel {background-color: red; padding: 10px 12px 10px 12px;}
                QLabel:hover {background-color: #C10000;}
            """)
            self.fileMenu.setTitle('Action 1')
        elif objectName == 'action2':
            self.label2.setStyleSheet("""
                QLabel { background-color : red; padding: 10px 12px 10px 12px;}
                QLabel:hover { background-color: #C10000;}
            """)
            self.fileMenu.setTitle('Action 2')
        elif objectName == 'action3':
            self.label3.setStyleSheet("""
                QLabel { background-color : red; padding: 10px 12px 10px 12px;}
                QLabel:hover { background-color: #C10000;}
            """)
            self.fileMenu.setTitle('Action 3')


QSS = """
#centralwidget {
    background-color: #18465d;
}

QMenuBar {
    background-color: qlineargradient(
        x1:0, y1:0, x2:0, y2:1,
        stop:0 lightgray, stop:1 darkgray);
    max-height: 35px;
    min-height: 35px;
    min-width: 140px;
    max-width: 140px;
    font: 22px;   
}
QMenuBar::item {
    background-color: #734046;
    color: rgb(255, 255, 255);  
    border-radius: 2px;
}
QMenuBar::item:selected {    
    background-color: rgb(244, 164, 96);  
}
QMenuBar::item:pressed {
    background: rgb(128, 0, 0);
}

QMenu {
    background-color: #ABABAB;   
    border: 1px solid black;
    margin: 2px;
}
QMenu::item {
    background-color: transparent;
    padding: 20px 25px 20px 20px;
}
QMenu::item:selected { 
    background-color: #654321;
    color: rgb(255,255,255);
}

QLabel { 
    background-color: #ABABAB;
    color: rgb(255, 255, 255);
    font: 20px;
    padding: 10px 12px 10px 12px;
} 
QLabel:hover { 
    background-color: #654321;
} 
"""

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    app.setStyleSheet(QSS)
    w = MainWindow()
    w.resize(400, 400)
    w.show()
    sys.exit(app.exec_())

现在我没有足够的声誉来提供任何截图,我稍后会附上额外的材料

-> 更新

введите сюда описание изображения

in this case, when element number 1 is selected, I need only this element to be painted in red.

为了更清楚,我将举一个来自 windows 的例子在此处输入图像描述

可以看到我在windows notepad中选择了lucida console字体,旁边有一条蓝色竖线。 这意味着当一个元素已经被选中时,一个特殊的样式会被应用到它上面

我希望你现在能理解我

这不能用样式表来实现,因为弹出视图中的选中项与组合的选中项不同,而只是用键盘(或鼠标悬停)选中的一项,与当前不对应组合的索引。

这样做的唯一方法是使用项目委托,它可以在组合上设置并将用于弹出窗口。

请注意,您显然需要对组合的引用来获取实际的当前索引,因此一种可能性(也是一种很好的做法)是以 combobox 作为父级来创建委托。

class SelectDelegate(QStyledItemDelegate):
    def initStyleOption(self, opt, index):
        super().initStyleOption(opt, index)
        if self.parent().currentIndex() == index.row():
            opt.backgroundBrush = QBrush(Qt.red)


class Test(QWidget):
    def __init__(self):
        super().__init__()
        self.comboBox = QComboBox()
        self.comboBox.setItemDelegate(
            SelectDelegate(self.comboBox))

        self.comboBox.addItem("1")
        self.comboBox.addItem("2")
        self.comboBox.addItem("3")

        layout = QVBoxLayout(self)
        layout.addWidget(self.comboBox)
        self.resize(150, 60)

请注意,您也可以使用 QItemDelegate,它通常更类似于默认的组合弹出窗口。

不幸的是,这有一个缺点,即视图可能看起来不像标准视图。

如果您没有使用自定义 model 并且您不需要背景 colors 进行其他任何操作,则有一种可能的替代方法,即在显示弹出窗口之前为所有项目设置BackgroundRole ,使用红色 QBrush 作为当前索引或None对于任何其他:

class SelectCombo(QComboBox):
    def showPopup(self):
        current = self.currentIndex()
        for i in range(self.count()):
            if i == current:
                color = QBrush(Qt.red)
            else:
                color = None
            self.setItemData(i, color, Qt.BackgroundRole)
        super().showPopup()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM