zl程序教程

您现在的位置是:首页 >  工具

当前栏目

QT-Qt设置背景图片

Qt 设置 背景图片
2023-09-14 08:57:11 时间

一、paintEvent法(平时没事,用在OSG中就不行了,因为TMD会一直调paintEvent事件,刷新到卡爆)

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 }
View Code

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
View Code

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 }
View Code

 

二、setStyleSheet方法

#include <QApplication>
#include <QtGui>

int main(int argc, char *argv[])
{
    QApplication app(argc,argv);
    QFrame *frame = new QFrame;
    frame->setObjectName("myframe");
    frame->resize(400,700);
    frame->setStyleSheet("QFrame#myframe{border-image:url(images/frame.png)}" );
    frame->show();

    return app.exec();
}

 

PS:注意需要增加资源文件。