简体   繁体   English

如何在不使用 QMainWindow 的情况下向 QWidget 添加背景图像?

[英]How to add a background image to a QWidget without using QMainWindow?

Edit: The problem is not solved yet, I used @Scheff s answer as a workaround temporarily.编辑:问题尚未解决,我暂时使用@Scheff的答案作为解决方法。

Is it possible to add an image as a background to a Qt widget application created with QWidget as a base class?是否可以将图像作为背景添加到使用 QWidget 作为基础 class 创建的 Qt 小部件应用程序中? I'm not using QMainWindow here at all.我根本没有在这里使用 QMainWindow。

In Qt Creator, you can generate skeleton source code files while creating a new project.在 Qt Creator 中,您可以在创建新项目的同时生成骨架源代码文件。 If you choose QWidget as a base class, and you try to add an image as a background by changing the widgets style sheet (wither manually or from the design section of the IDE), The image doesn't show up when you build the project.如果您选择 QWidget 作为基础 class,并且您尝试通过更改小部件样式表(手动枯萎或从 IDE 的设计部分)添加图像作为背景,则构建项目时图像不会显示. How can I fix this if it's possible?如果可能的话,我该如何解决这个问题?

I create a Qt Resource File, add an image (which is in the source code directory), and set the style sheet, That's it.我创建一个 Qt 资源文件,添加一个图像(在源代码目录中),并设置样式表,就是这样。 But if I add a background color with但是如果我添加背景颜色

Widget->setStyleSheet(QString::fromUtf8("#Widget {background-color: rgb(55,55,55)};")); 

in ui_widget.h , It works fine and shows up after build.ui_widget.h中,它工作正常并在构建后显示。

And if I preview the widget from inside Qt Creator, the image appears, but doesn't after building and running.如果我从 Qt Creator 中预览小部件,图像会出现,但在构建和运行后不会出现。

Here you choose QWidget as a Base class in Qt Creator:在这里,您在 Qt Creator 中选择 QWidget 作为基础 class:

在 Qt Creator 中创建一个新项目

This is main.cpp:这是 main.cpp:

#include "widget.h"
#include <QtCore/qglobal.h>
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

This is ui_widget.h:这是 ui_widget.h:

#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>

QT_BEGIN_NAMESPACE
class Ui_Widget
{ 
public:
    void setupUi(QWidget *Widget)
    {
        if (Widget->objectName().isEmpty())
            Widget->setObjectName(QString::fromUtf8("Widget"));
        Widget->resize(600, 150);

        // I add this line, if I changed the style sheet to a simple background color it shows up with no problem {background-color: rgb(1,1,200)}
        Widget->setStyleSheet(QString::fromUtf8("#Widget {background-image: url(:/pic.jpg);}"));

        retranslateUi(Widget);
        QMetaObject::connectSlotsByName(Widget);
    } // setupUi

    void retranslateUi(QWidget *Widget)
    {
        Widget->setWindowTitle(QApplication::translate("Widget", "Widget", nullptr));
    } // retranslateUi

};

namespace Ui {
    class Widget: public Ui_Widget {};
} // namespace Ui

QT_END_NAMESPACE

This is widget.h:这是widget.h:

#include <QtCore/qglobal.h>
#include <QtWidgets/QWidget>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT
public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
private:
    Ui::Widget *ui;
};

This is widget.cpp:这是widget.cpp:

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); }

Widget::~Widget() { delete ui; }

Sorry for adding the whole generated code but it might be helpful, Thanks.很抱歉添加了整个生成的代码,但它可能会有所帮助,谢谢。

Out of curiosity, I tried on my side with my own MCVE .出于好奇,我尝试了自己的MCVE

C++ source testQWidgetBackgroundImage.cc : C++ 源码testQWidgetBackgroundImage.cc

// Qt header:
#include <QtWidgets>

// main application
int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  QWidget qWinMain;
  qWinMain.setWindowTitle("Test Background Image");
  qWinMain.resize(640, 480);
  qWinMain.setObjectName("Widget");
  qWinMain.setStyleSheet("#Widget { background-image: url(cat.jpg); }");
  qWinMain.show();
  // runtime loop
  return app.exec();
}

Build script CMakeLists.txt :构建脚本CMakeLists.txt

project(QWidgetBackgroundImage)

cmake_minimum_required(VERSION 3.10.0)

set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

find_package(Qt5Widgets CONFIG REQUIRED)

include_directories("${CMAKE_SOURCE_DIR}")

add_executable(testQWidgetBackgroundImage testQWidgetBackgroundImage.cc)

target_link_libraries(testQWidgetBackgroundImage Qt5::Widgets)

Output: Output:

testQWidgetBackgroundImage.exe 的快照

So, I was able to show a plain QWidget with a background image set by a style sheet, at least, in Windows 10 with VS 2017 and Qt 5.13.因此,我至少能够在带有 VS 2017 和 Qt 5.13 的 Windows 10 中显示一个带有由样式表设置的背景图像的普通QWidget

This is in accordance with what is documented in Qt Style Sheets Reference – background :这与Qt 样式表参考 - 背景中记录的内容一致:

Shorthand notation for setting the background.用于设置背景的简写符号。 Equivalent to specifying background-color, background-image, background-repeat, and/or background-position.等效于指定背景颜色、背景图像、背景重复和/或背景位置。

This property is supported by QAbstractItemView subclasses, QAbstractSpinBox subclasses, QCheckBox, QComboBox, QDialog, QFrame, QGroupBox, QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QRadioButton, QSplitter, QTextEdit, QToolTip, and plain QWidgets. QAbstractItemView 子类、QAbstractSpinBox 子类、QCheckBox、QComboBox、QDialog、QFrame、QGroupBox、QLabel、QLineEdit、QMenu、QMenuBar、QPushButton、QRadioButton、QSplitter、QTextEdit、QToolTip 和普通 QWidget 支持此属性。

Note:笔记:

I must admit that I don't have any experience concerning the use of Qt resources.我必须承认,我没有任何使用 Qt 资源的经验。 Hence, I provided the URL just as url(cat.jpg) which results in the attempt to load from a file in the local current working directory (with success as seen in the snapshot above).因此,我提供了 URL 就像url(cat.jpg)这导致尝试从本地当前工作目录中的文件加载(成功如上面的快照所示)。 The prefixing with : (eg url(:/cat.jpg) ) would address an entry in the Qt resources instead.带有:的前缀(例如url(:/cat.jpg) )将解决 Qt 资源中的条目。

Further readings: The Qt Resource System进一步阅读: Qt 资源系统


After having read the doc.在阅读了文档之后。 in the above link, I noticed that it's not that complicated to use and modified the above MCVE a bit:在上面的链接中,我注意到使用起来并不复杂,并稍微修改了上面的 MCVE:

C++ source file testQWidgetBackgroundImage.cc C++源文件testQWidgetBackgroundImage.cc

// Qt header:
#include <QtWidgets>

// main application
int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  QWidget qWinMain;
  qWinMain.setWindowTitle("Test Background Image");
  qWinMain.resize(640, 480);
  qWinMain.setObjectName("Widget");
  qWinMain.setStyleSheet("#Widget { background-image: url(:/cat.jpg); }");
  qWinMain.show();
  // runtime loop
  return app.exec();
}

Effectively, the only change was url(cat.jpg)url(:/cat.jpg) .实际上,唯一的变化是url(cat.jpg)url(:/cat.jpg)

Qt resource file testQWidgetBackgroundImage.qrc : Qt 资源文件testQWidgetBackgroundImage.qrc

<!DOCTYPE RCC>
<RCC version="1.0">
  <qresource>
    <file>cat.jpg</file>
  </qresource>
</RCC>

Qt project file testQWidgetBackgroundImage.pro : Qt 项目文件testQWidgetBackgroundImage.pro

SOURCES = testQWidgetBackgroundImage.cc

RESOURCES = testQWidgetBackgroundImage.qrc

QT += widgets

Built and tested in cygwin64 :cygwin64中构建和测试:

$ qmake-qt5 testQWidgetBackgroundImage.pro

$ make && ./testQWidgetBackgroundImage 
g++ -c -fno-keep-inline-dllexport -D_GNU_SOURCE -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -isystem /usr/include/qt5 -isystem /usr/include/qt5/QtWidgets -isystem /usr/include/qt5/QtGui -isystem /usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o testQWidgetBackgroundImage.o testQWidgetBackgroundImage.cc
/usr/lib/qt5/bin/rcc -name testQWidgetBackgroundImage testQWidgetBackgroundImage.qrc -o qrc_testQWidgetBackgroundImage.cpp
g++ -c -fno-keep-inline-dllexport -D_GNU_SOURCE -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -isystem /usr/include/qt5 -isystem /usr/include/qt5/QtWidgets -isystem /usr/include/qt5/QtGui -isystem /usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o qrc_testQWidgetBackgroundImage.o qrc_testQWidgetBackgroundImage.cpp
g++  -o testQWidgetBackgroundImage.exe testQWidgetBackgroundImage.o qrc_testQWidgetBackgroundImage.o   -lQt5Widgets -lQt5Gui -lQt5Core -lGL -lpthread 
Qt Version: 5.9.4

Output: Output:

./testQWidgetBackgroundImage 的快照

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM