Qt设置所有对话框的公共背景

时间:2017-08-18 10:32:21

标签: c++ qt qt5

我正在开发一个Qt 5小部件桌面应用程序,我想为弹出的所有窗口和对话框提供一个通用背景。问题是,对于每个窗口,我必须一遍又一遍地指定相同的代码片段以加载相同的背景。我还使用paint函数覆盖,以便在调整窗口大小时不扭曲背景。这是我的代码:

SettingsDialog::SettingsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);
    pixmapBg.load(":/images/google-material-design-wallpaper-10.jpg");
}
void SettingsDialog::paintEvent(QPaintEvent *pe)
{
        QPixmap pixmapBgL = pixmapBg.scaled(this->size());
        QPalette palette;
        palette.setBrush(QPalette::Background, pixmapBgL);
        this->setPalette(palette);
}

有没有办法在Qt中使用单个文件来容纳这个,而不是为每个窗口提及它?

2 个答案:

答案 0 :(得分:0)

是的,你可以!您必须提供own stylesheet,或通过致电QApplication::setStyleSheet(styleName)来初始化您的申请。

评论后续跟进:setStyleSheet是最快的方法,即

qApp->setStyleSheet("QDialog, QMessageBox {background-image: url(:/images/google-material-design-wallpaper-10.jpg);}");

假设您有一个有效的QApplication引用qApp。请注意,如果要优化样式表的范围,也可以引用自定义子类。

答案 1 :(得分:0)

以下是一些使用QApplication :: setStyleSheet的代码:

QString styleSheet = "QWidget{\
                              background-color: yellow\
                             }"//style sheet in CSS style

int main(int argc, char** argv){
    QApplication app(argc, argv);
    app.setStyleSheet(styleSheet);//will set all the QWidgets' background color to yellow
    return app.exec();
}

实际上有背景图片属性,但我不确定哪些小部件支持它,因此您可以正确检查there