Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting style by object #id in PyQt5

I have 2 files in my project: main.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, QApplication)
from styles import styles

class MyApp(QWidget):
def __init__(self):
    super().__init__()
    self.initUI()

def initUI(self):
    self.setStyleSheet(styles)
    btn1 = QPushButton('Button1', self)
    btn1.resize(btn1.sizeHint())
    btn1.move(50, 50)
    btn2 = QPushButton('Button2', self)
    btn2.resize(btn2.sizeHint())
    btn2.move(100, 100)
    self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    my = MyApp()
    sys.exit(app.exec_())

and styles.py:

styles="QPushButton#btn2 { background-color: red }"

As stated here this one should change the background color of the btn2. However, it does nothing. What's wrong?

styles="QPushButton { background-color: red }"

works fine (for all instances of QPushButton class). I'm working with PyQt5 and Python 3.5

like image 852
Oleh Avatar asked Feb 05 '23 21:02

Oleh


1 Answers

OK, that's how it works: I firstly have to set the name of the object I want to reference in the stylesheet. Like:

self.btn2.setObjectName('btn2')

After this

styles="QPushButton#btn2 { background-color: red }" 

worked OK.

like image 135
Oleh Avatar answered Feb 07 '23 11:02

Oleh