pyqt:为什么加载的 qss 文件不起作用 [英] pyqt: why the loaded qss file do not work

查看:101
本文介绍了pyqt:为什么加载的 qss 文件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的项目中加载 qss 文件.我发现它不起作用.

I am loading qss file in my project. And I find it do not work.

我的 qss 文件是:

My qss file is:

QMainWindow
{
    font-size: 20px;
    background: rgb(255, 0, 0);
}

我的代码是:

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

import sys

class Win(QMainWindow):

    def __init__(self):
        super().__init__()

        with open('style.qss', 'r', encoding='utf-8') as file:
            str = file.read()
        self.setStyleSheet(str)

        self.__widget = QWidget()
        self.setCentralWidget(self.__widget)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    win = Win()
    win.show()
    app.exec_()

然而,显示窗口的背景颜色不是红色.

However, the background color of showed window is not red.

-------------------- 更新----------------------------------------

-------------------- update --------------------------------------

根据@musicamante 的建议,我尝试在 QMainWindow 中添加一个覆盖的 QWidget.但是,它仍然不起作用.

According to the suggestion of @musicamante, I try that add a overwrited QWidget in the QMainWindow. However, it still do not work.

推荐答案

您的代码有两个问题:

  1. 当使用大括号 ({ property: value; }) 语法时,selector 是强制性的(请参阅 选择器类型),否则根本不应该使用括号(但是这通常是不受欢迎的);
  2. 在为普通 QWidget 设置样式时,paintEvent() 必须 被覆盖(请参阅相关的 样式表文档中的 QWidget 参考);
  1. when using the curly brackets ({ property: value; }) syntax, the selector is mandatory (see the selector types), otherwise no brackets should be used at all (but that's usually frown upon);
  2. when styling a plain QWidget, the paintEvent() must be overridden (see the related QWidget reference on the stylesheet documentation);

使用给定的代码,样式表语法应如下(注意星号):

With the given code, the stylesheet syntax should be the following (note the asterisk):

* {
    font-size: 20px;
    background: rgb(255, 0, 0);
}

在为基本 QWidget(或在 Python 中创建的 QWidget 子类)设置样式时,还需要以下内容:

When styling a basic QWidget (or a QWidget subclass created in python), the following is also required:

class SomeCustomWidget(QWidget):
    # ...
    def paintEvent(self, event):
        qp = QPainter(self)
        opt = QStyleOption()
        opt.initFrom(self)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, qp, self)


class Win(QMainWindow):
    def __init__(self):
        # ...
        self.__widget = SomeCustomWidget()
        self.setCentralWidget(self.__widget)

这篇关于pyqt:为什么加载的 qss 文件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆