在PyQt5中按对象#id设置样式

时间:2017-03-11 13:59:40

标签: python css python-3.x pyqt5 python-3.6

我的项目中有2个文件: 的 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_())

styles.py

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

如前所述here这个应该改变btn2的背景颜色。但是,它什么也没做。怎么了?

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

工作正常(适用于QPushButton类的所有实例)。我正在使用PyQt5和Python 3.5

1 个答案:

答案 0 :(得分:1)

好的,它是如何工作的:我首先必须在样式表中设置我想要引用的对象的名称。 喜欢:

self.btn2.setObjectName('btn2')

在此之后

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

工作正常。