python - 使用 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()
举个例子 :
- setButton去除背景色、边框、白字……
- 窗口更改背景颜色
谢谢您的帮助
解决方案
无需更改 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())
而且由于您在父小部件上设置了样式,所有子小部件(包括您的按钮)也将具有相同的样式。
推荐阅读
- apache-kafka - 卡夫卡连接不起作用?
- ios - 返回 xcode/swift/ios 项目 - 突然得到“没有这样的模块”
- aspnetboilerplate - 带有 JavaScript 的菜单项
- android - 如何跟踪用户吸引我的广告的时间
- sql - 如何在 postgresql 中获取组号?
- php - php数组迭代视觉上父>子
- android - android Polyline会在一段时间后滞后地图
- mysql - 我在将 mysql 数据库(phpmyadmin)连接到 node.js 时收到错误
- csv - Spark:正在写入的加载文件
- php - Symfony - 控制器编辑动作