如何为Qt应用程序的整个窗口设置背景颜色?

bry*_*yce 26 c++ qt qstylesheet qwindow

有谁知道如何能够为Qt应用程序的整个窗口设置背景颜色?

到目前为止,我正在使用样式表,但只能弄清楚如何为窗口小部件分配背景颜色,如QGroupBoxQPushButton.基本上,如果我想要黑色背景,如何在没有原始背景边框的情况下使其无缝化?

Jér*_*ôme 27

我只想在整个窗口中使用样式表.

例如,如果您的窗口继承自QWidget,那么我正在做的事情:

MainWindow::MainWindow(QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setStyleSheet("background-color: black;");
}
Run Code Online (Sandbox Code Playgroud)

在我的Mac上,我的整个应用程序窗口是黑色的(标题栏除外).

编辑:根据评论,这是一个不使用ui文件和加载外部样式表的解决方案

#include <QtGui/QApplication>
#include <QtGui/QMainWindow>
#include <QtGui/QVBoxLayout>
#include <QtGui/QPushButton>
#include <QtCore/QFile>

int main(int ArgC, char* ArgV[])
{
QApplication MyApp(ArgC, ArgV);

QMainWindow* pWindow = new QMainWindow;
QVBoxLayout* pLayout = new QVBoxLayout(pWindow);
pWindow->setLayout(pLayout);

QPushButton* pButton = new QPushButton("Test", pWindow);
pLayout->addWidget(pButton);

QFile file(":/qss/default.qss");
file.open(QFile::ReadOnly);
QString styleSheet = QLatin1String(file.readAll());

qApp->setStyleSheet(styleSheet);

pWindow->setVisible(true);
MyApp.exec();
}
Run Code Online (Sandbox Code Playgroud)

样式表文件(default.qss)如下:

QWidget {
  background-color: black;
}
Run Code Online (Sandbox Code Playgroud)

此文件是资源文件(stylesheet.qrc)的一部分:

<RCC>
  <qresource prefix="/qss">
    <file>default.qss</file>
  </qresource>
</RCC>
Run Code Online (Sandbox Code Playgroud)

这是我的项目文件:

TARGET = StyleSheet
TEMPLATE = app
SOURCES += main.cpp
RESOURCES += stylesheet.qrc
Run Code Online (Sandbox Code Playgroud)


Dir*_*tel 13

这对我有用:

a = new QApplication(argc, argv);
QPalette pal = a->palette();
pal.setColor(QPalette::Window, Qt::white);
a->setPalette(pal);
Run Code Online (Sandbox Code Playgroud)


小智 5

只需添加

setStyleSheet("background-color: white;");
Run Code Online (Sandbox Code Playgroud)

对于您的代码,您可以直接提供任何颜色。