main.cpp

1 #include "mainwindow.h" 2 3 #include <QApplication> 4 5 int main(int argc, char *argv[]) 6 { 7 QApplication a(argc, argv); 8 MainWindow w; 9 w.show(); 10 return a.exec(); 11 }
mainwindow.h

1 #ifndef MAINWINDOW_H 2 #define MAINWINDOW_H 3 4 #include <QMainWindow> 5 #include <QPainter> 6 7 QT_BEGIN_NAMESPACE 8 namespace Ui { class MainWindow; } 9 QT_END_NAMESPACE 10 11 class MainWindow : public QMainWindow 12 { 13 Q_OBJECT 14 15 public: 16 MainWindow(QWidget *parent = nullptr); 17 ~MainWindow(); 18 19 void paintEvent(QPaintEvent* pEvent); 20 private: 21 Ui::MainWindow *ui; 22 }; 23 #endif // MAINWINDOW_H
mainwindow.cpp

1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 4 MainWindow::MainWindow(QWidget *parent) 5 : QMainWindow(parent) 6 , ui(new Ui::MainWindow) 7 { 8 ui->setupUi(this); 9 resize(200, 100); 10 setWindowTitle(QStringLiteral("Qt设置背景图片")); 11 } 12 13 MainWindow::~MainWindow() 14 { 15 delete ui; 16 } 17 18 void MainWindow::paintEvent(QPaintEvent *pEvent) 19 { 20 // 界面背景图片片 21 QPainter painter(this); 22 painter.drawPixmap(0, 0, this->width(), this->height(), QPixmap(":/new/image/ABC.jpg")); 23 }
PS:注意需要增加资源文件。