简体   繁体   中英

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

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM