Reputation: 139
I use Python 3.7 and Pyside2.
I would like to change color, font, background color... but I can not !
I import QtGui for design but I have the same error '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()
For exemple :
Thank you for your help
Upvotes: 0
Views: 1743
Reputation: 1417
Instead of changing the Painter just use a stylesheet. Qt stylesheets use CSS syntax and can be easily reused for multiple widgets. More info here: https://doc.qt.io/qt-5/stylesheet-syntax.html
In your case for example you could replace
self.setBrush(QColor(255, 0, 0, 127))
with
self.setStyleSheet('background-color: rgb(0, 0, 127)')
to change the background color to Blue.
To make it reusable though it would make sense to put the Stylesheet into a seperate file. Place the stylesheet in the same folder as your Python file.
style.qss:
QWidget {
background-color: rgb(0, 0, 127);
}
QPushButton {
border: none;
color: white;
}
And then replace
self.setBrush(QColor(255, 0, 0, 127))
with
# 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())
And since you set the style on the parent widget all child widgets (including your Button) will have the same style aswell.
Upvotes: 1