有没有办法更改所有QMessageBox的OK按钮的样式表?

我想让我的所有QMessageBoxGUI的 OK 按钮(它非常复杂,所以有很多)相对于其他按钮(取消、否等)设置不同的颜色。

我不想在每次创建新的时都设置它的颜色,QMessageBox但我想通过我的应用程序的样式表一劳永逸地设置它。

我尝试了不同的选择,但都没有奏效:

 - QMessageBox#okButton {background-color:blue}
 - QMessageBox::okButton {...}
 - QMessageBox:okButton {...}
 - QMessageBox#ok-button {...}
 - QMessageBox QPushButton#okButton {...}

和别的...

有没有办法或者我必须放弃?

回答

一个可能的解决方案是将 设置objectName()为每个按钮的选择器,为此您可以使用 的notify()方法QApplication

from PySide2.QtCore import QEvent
from PySide2.QtWidgets import *


class Application(QApplication):
    def notify(self, receiver, event):
        if isinstance(receiver, QMessageBox) and event.type() == QEvent.Show:
            for button in receiver.buttons():
                sb = receiver.standardButton(button)
                if not button.objectName():
                    button.setObjectName(sb.name.decode())
                    button.style().unpolish(button)
                    button.style().polish(button)
        return super().notify(receiver, event)


def main():
    app = Application()
    app.setStyle("fusion")

    app.setStyleSheet(
        """
    QPushButton#Ok { background-color: green }
    QPushButton#Cancel { background-color: red }
    """
    )

    QMessageBox.critical(
        None, "Title", "text", buttons=QMessageBox.Ok | QMessageBox.Cancel
    )

    msgBox = QMessageBox()
    msgBox.setText("The document has been modified.")
    msgBox.setInformativeText("Do you want to save your changes?")
    msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
    msgBox.exec_()


if __name__ == "__main__":
    main()


以上是有没有办法更改所有QMessageBox的OK按钮的样式表?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>