0

所以我在样式表中调用了一个 Qt StyleSheetmain.qss我试图设置宽度和高度它不起作用它只是保持不变。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 支持边距。

4

1 回答 1

1

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

  1. widthheight)属性通常不适用于小部件,而仅适用于子控件,如文档中所述

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

  1. “点”分隔符不像在 python 中那样工作,但就像在 css 中那样:它是一个选择器

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

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

    QPushButton#menuButton {...}

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

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

样式表框模型

因此,您设置的填充位于按钮边框和内容(图标和/或文本,即 QStyleSE_PushButtonContents子元素)之间。您正在寻找的是margin

于 2021-06-14T17:07:38.897 回答