1

我选择使用 Qt 来管理我正在处理的项目的 GUI。

在我的底部找到如何应用图片后QWidget,我注意到它对添加到其中的所有组件都有影响。

无论通过该setStyleSheet方法应用什么样式,甚至使用 a QPixmap,这些元素的背景始终是为QWidget容器定义的图像。

我怎样才能避免这种行为?

这是我的代码:

MainMenu::MainMenu(QWidget* Parent, const QPoint& Position, const QSize& Size) : QWidget(Parent) {

    QString qwidgetStyle = "QWidget {background-image: url(background.jpg); border: 5px solid rgba(3, 5, 28, 1);}";
    QString buttonStyle = "color: rgba(73, 123, 176, 1); font-size:30px; background-color: rgba(73, 123, 176, 1);";

    move(Position);
    resize(Size);   
    setStyleSheet(qwidgetStyle);

    // Menu title
    QLabel *title = new QLabel(this);
    title->setText("Menu");
    title->setStyleSheet(buttonStyle);
    title->setAlignment(Qt::AlignCenter);

    // Menu buttons
    // Play
    buttonPlay = new QPushButton("Play");
    (*buttonPlay).setEnabled(true);
    (*buttonPlay).setStyleSheet(buttonStyle);
    connect(buttonPlay, SIGNAL(clicked()), this, SLOT(handleButton()));
    // Option
    buttonOptions = new QPushButton("Options", this);
    (*buttonOptions).setEnabled(true);
    (*buttonOptions).setGeometry(250, 175, 100, 50);
    (*buttonOptions).setStyleSheet(buttonStyle);
    connect(buttonOptions, SIGNAL(clicked()), this, SLOT(handleButton()));
    // Quit
    buttonQuit = new QPushButton("Quit", this);
    (*buttonQuit).setEnabled(true);
    (*buttonQuit).setGeometry(250, 275, 100, 50);
    (*buttonQuit).setStyleSheet(buttonStyle);
    connect(buttonQuit, SIGNAL(clicked()), this, SLOT(handleButton()));

    // Layout
    QGridLayout *layout = new QGridLayout;
    layout->setMargin(50);
    layout->addWidget(title, 0, 0, 1, 5);
    layout->addWidget(buttonPlay, 3, 1, 2, 3);
    layout->addWidget(buttonOptions, 4, 1, 2, 3);
    layout->addWidget(buttonQuit, 5, 1, 2, 3);
    setLayout(layout);

    show();
}
4

1 回答 1

3

由于以下几行,您遇到的行为是完全正常的:

QString qwidgetStyle = "QWidget {background-image: url(background.jpg); border: 5px solid rgba(3, 5, 28, 1);}";
...
setStyleSheet(qwidgetStyle);

在这里,您只是告诉 Qt 应用qwidgetstyle您的应用程序的每个 QWidget,使用关键字QWidget。这就是为什么在 Qt 中,如果要将样式应用于此特定对象,则最好为对象设置名称。

在您的代码中,QLabel并且QPushButton两者都继承自QWidget,因此它们将具有您为 a 定义的样式QWidget除非您为它们命名或为每个指定样式

如果你想为你的MainMenu直接继承的设置样式表QWidget(这是你首先要做的),你必须设置一个名称,然后应用样式:

setObjectName("MainMenu");
QString qwidgetStyle = "QWidget#MainMenu {background-image: url(background.jpg); border: 5px solid rgba(3, 5, 28, 1);}";
setStyleSheet(qwidgetStyle);  // here, only your MainMenu will have the style "qwidgetstyle"

请注意,例如,您可以为每个 设置相同的样式表QWidget,并且只为您的 : 添加特定颜色MainMenu

// this is in a CSS, but you can apply it directly from the MainMenu constructor of course
QWidget, QWidget#MainMenu {
    background-image: url(background.jpg); 
    border: 5px solid rgba(3, 5, 28, 1);
} // aplied to all QWidget

QWidget#MainMenu { 
    color : #9b9b9b; // a nice grey, only applied to MainMenu
}

同样,在使用样式表时要具体,否则您最终会在应用程序中到处出现奇怪的颜色/对齐方式:)。希望有帮助!

注意:您还可以感谢@PaulRooney,他在评论中提供了一个非常好的链接。

于 2016-05-18T13:13:54.640 回答