如何将样式表应用于 PyQt 中的自定义小部件 [英] How to apply style sheet to a custom widget in PyQt

查看:51
本文介绍了如何将样式表应用于 PyQt 中的自定义小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

# -*- coding: utf-8 -*-

import sys
from PyQt4.QtGui import *  
from PyQt4.QtCore import * 

class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setFixedWidth(200)
        self.setFixedHeight(200)

        stylesheet = \
            ".QWidget {\n" \
            + "border: 20px solid black;\n" \
            + "border-radius: 4px;\n" \
            + "background-color: rgb(255, 255, 255);\n" \
            + "}"
        self.setStyleSheet(stylesheet)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

我想为带有样式表的自定义小部件添加边框,但样式表似乎不起作用,有什么问题吗?

I want to add a border to a custom widget with style sheet, but the style sheet does not seem to work, anything wrong?

推荐答案

首先:向示例中添加一个实际的小部件:

Firstly: add an actual widget to your example:

    self.widget = QWidget(self)
    layout = QVBoxLayout(self)
    layout.addWidget(self.widget)

其次:帮自己一个忙,并使用三重引号:

Secondly: do yourself a favour, and use triple-quotes:

    self.widget.setStyleSheet("""
        QWidget {
            border: 20px solid black;
            border-radius: 10px;
            background-color: rgb(255, 255, 255);
            }
        """)

您示例中的点选择器是多余的.它的作用是指定只选择 QWidget 本身的实例,而不是 QWidget 的子类.请参阅 Qt 文档中的样式表语法指南.

The dot-selector in your example is redundant. What it does is specify that only instances of QWidget itself will be selected, as opposed to sub-classes of QWidget. See the StyleSheet Syntax guide in the Qt docs.

这篇关于如何将样式表应用于 PyQt 中的自定义小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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