Good day, colleagues, I have a styles, example:
#button_1 {
background-color: green;
}
#button_2 {
background-color: red;
}
I have 3 objects:
button_1 = QPushButton()
button_2 = QPushButton()
button_3 = QPushButton()
And I want after click on button_1
set to this button style #button_1, I change the name of this button
button_1.setObjectName('button_1')
but after it button style not change, (but css load correct it's worked), and I have a question, maybe I need to reload or do smth with this button to set this style for it and it should be work.
I use python version 3.10 and pyside6 version 6.4.1
Full code of app:
from PySide6.QtWidgets import QHBoxLayout, QWidget, QPushButton, QApplication
import sys
class App(QWidget):
def __init__(self) -> None:
super().__init__()
self.load_ui()
def load_ui(self):
self.setStyleSheet("""
#button_1 {
background-color: green;
}
#button_2 {
background-color: red;
}
""")
self.button_1 = QPushButton()
self.button_2 = QPushButton()
self.button_3 = QPushButton()
self.app_layout = QHBoxLayout()
self.app_layout.addWidget(self.button_1)
self.app_layout.addWidget(self.button_2)
self.app_layout.addWidget(self.button_3)
self.setLayout(self.app_layout)
self.button_1.clicked.connect(self.button_1_click)
def button_1_click(self):
print('clicked')
self.button_1.setObjectName('button_1')
if __name__ == "__main__":
app = QApplication(sys.argv)
main_window_widget = App()
main_window_widget.show()
sys.exit(app.exec_())
Maybe try changing the name and then parsing the stylesheet.
Also instead make the stylesheet button specific so that when you call it its like this:
self.button1.setStyleSheet("background-color: #8a78f0; border-style: none; border-width: 2px; border-radius: 5px; ")
This will change the widget specifically by calling it onto the object.
Also please provide more code so that we can reproduce the error as I don't not have enough information to provide optimal assistance.
However, using a specific stylesheet like the code above may do the trick.
For correctly work all styles, after change the name I make reload all styles. Example:
In app class I add:
def load_styles(self):
with open('styles.css', 'r') as file:
self.setStyleSheet(file.read())
After that, after change the name, I call this method:
def button_1_click(self):
print('clicked')
self.button_1.setObjectName('button_1')
self.load_styles()
Not good solve, but another I doesn't have:(
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.