【问题标题】:Width, Height, and Margin doesn't work in QT Style Sheet in PySide6宽度、高度和边距在 PySide6 的 QT 样式表中不起作用
【发布时间】:2021-08-30 14:01:18
【问题描述】:

所以我在样式表中有一个名为main.qss 的Qt StyleSheet,我试图设置宽度和高度它不起作用它只是保持不变。 Margins 也会发生同样的情况。

这是 QSS:

QFrame#mainFrame {
    background-color: #282C34;
}

QFrame#menuFrame {
    background-color: #21252B;
}

QPushButton.menuButton {
    background-color: #21252B;

    padding-left: 12px;
    padding-top: 1px;
    padding-bottom: 1px;

    border: 0;
    font-family: "Times New Roman";
    font-size: 20pt;

    color: #FFFFFF;

    width: 300pt; <-- Problem here
    height: 15px; <-- Problem here
}

QPushButton.menuButton:hover {
    background-color: #282C34;
}

QPushButton.menuButton:pressed {
    background-color: #BD93F9;
}

这是我的 QPushButton:

self.menu_toggle_button = QtWidgets.QPushButton(self.menu_frame)
self.menu_toggle_button.setIcon(QtGui.QPixmap("menu_icons/menu.png"))
self.menu_toggle_button.setText("  Hide")
self.menu_toggle_button.setObjectName("menuToggleButton")
self.menu_toggle_button.setProperty("class", "menuButton")
self.menu_toggle_button.setIconSize(QtCore.QSize(20, 20))

那我做错了什么?

我知道这是可行的,因为在 Qt 样式表参考中,可以在这里找到:https://doc.qt.io/qtforpython-6/overviews/stylesheet-reference.html?highlight=stylesheet,它说 QPushButton 支持宽度、高度和边距。

【问题讨论】:

  • "它说 QPushButton 支持宽度、高度和边距。"你在哪里看到的?也许您指的是max-widthmin-width。实际上,width 属性有一个明确的警告:“除非另有说明,否则在小部件上设置此属性时无效。”
  • @musicamante 谢谢musicamante 这解决了我的宽度和高度问题,但是边距怎么办,因为这些仍然不起作用。

标签: python python-3.x pyside qtstylesheets pyside6


【解决方案1】:

您的样式表不起作用有两个原因:

  1. width(和height)属性通常不适用于小部件,而仅适用于子控件,如explained in the docs

警告:除非另有说明,否则此属性在小部件上设置时无效。如果你想要一个固定宽度的小部件,请将 min-width 和 max-width 设置为相同的值。

  1. “点”分隔符不像在 python 中那样起作用,但在 css 中起作用:它是class selector

.QPushButton 匹配 QPushButton 的实例,但不匹配它的子类。

如果你想匹配objectName属性,你需要ID选择器

    QPushButton#menuButton {...}

考虑到虽然 Qt 样式表支持这些属性,但通常最好将这些设置留给布局管理器并直接使用小部件功能(setFixedSize()setFixedWidth()setFixedHeight())。

最后,边距不起作用,因为您使用的是 padding。 Qt 也为Box Model 使用了与 CSS 相同的概念:

因此,您设置的填充位于按钮的 bordercontent(图标和/或文本,即 QStyle SE_PushButtonContents sub元素)。您正在寻找的是 margin

【讨论】:

  • 这解决了我的问题,非常感谢,但是我的自定义类选择器确实有效,您可以通过这样做来创建自己的自定义类选择器:widget.setProperty("class", "custom class") 然后您可以在qt 样式表
猜你喜欢
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 2012-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-18
相关资源
最近更新 更多