首页 > 解决方案 > 使用 Pyside2 - Python3 改变设计

问题描述

我使用 Python 3.7 和 Pyside2。

我想改变颜色、字体、背景颜色……但我不能!

我导入 QtGui 进行设计,但我有同样的错误'Window' object has no attribute 'setBrush'

from PySide2.QtGui import QColor, QBrush, QPainterPath, QFont
from PySide2.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QDesktopWidget

import sys

class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Convertisseur de devises")
        self.setGeometry(700,300,700,300)
        self.setBrush(QColor(255, 0, 0, 127))

        self.setButton()
        self.center()

    def setButton(self):
        btn = QPushButton("Inverser Devises", self)
        btn.move(550,135)

    def center(self):
        qRect = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qRect.moveCenter(centerPoint)
        self.move(qRect.topLeft())

myapp = QApplication(sys.argv)
window = Window()
window.show()

myapp.exec_()
sys.exit()

举个例子 :

谢谢您的帮助

标签: pythonpython-3.xpyside2

解决方案


无需更改 Painter,只需使用样式表。Qt 样式表使用 CSS 语法,可以轻松地用于多个小部件。更多信息:https ://doc.qt.io/qt-5/stylesheet-syntax.html

例如,在您的情况下,您可以替换

self.setBrush(QColor(255, 0, 0, 127))

self.setStyleSheet('background-color: rgb(0, 0, 127)')

将背景颜色更改为蓝色。

为了使其可重用,尽管将样式表放入单独的文件中是有意义的。将样式表放在与 Python 文件相同的文件夹中。

样式.qss:

QWidget {
    background-color: rgb(0, 0, 127);
}

QPushButton {
    border: none;
    color: white;
}

然后替换

self.setBrush(QColor(255, 0, 0, 127))

# This gets the folder the Python file is in and creates the path for the stylesheet
stylesheet_path = os.path.join(os.path.dirname(__file__), 'style.qss')

with open(stylesheet_path, 'r') as f:
    self.setStyleSheet(f.read())

而且由于您在父小部件上设置了样式,所有子小部件(包括您的按钮)也将具有相同的样式。


推荐阅读