【问题标题】:Setting style by object #id in PyQt5在 PyQt5 中通过对象#id 设置样式
【发布时间】:2017-03-11 13:59:39
【问题描述】:

我的项目中有 2 个文件: ma​​in.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

【问题讨论】:

  • 您的代码中没有具有该 ID 的对象。事实上,代码中的所有对象都没有 id。

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


【解决方案1】:

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

self.btn2.setObjectName('btn2')

之后

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

工作正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 2020-11-15
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多