qt5--paintEvent繪圖事件


窗口改變或調用update()/repaint()函數會觸發這個事件

當update()函數被調用多次,或者窗口系統發送了多個重繪事件,那么Qt就會合並這些事件成為一個事件,而這個事件擁有最大的需要重繪的區域。update()函數不會立即進行重繪,要等到Qt返回主事件循環后才會進行,所以多次調用update()函數一般只會引起一次paintEvent()函數調用

調用repaint()函數會立即調用paintEvent()函數來重繪部件,只有在必須立即進行重繪操作的情況下(比如在動畫中),才使用repaint()函數

update()函數允許Qt優化速度和減少閃爍,但是repaint()函數不支持這樣的優化,所以建議一般情況下盡可能使用update()函數

實例

h文件

#ifndef WIN_H
#define WIN_H

#include <QWidget>
#include<QImage>  //圖片對象
#include<QPainter>  //畫家類

QT_BEGIN_NAMESPACE
namespace Ui { class Win; }
QT_END_NAMESPACE

class Win : public QWidget
{
    Q_OBJECT

public:
    Win(QWidget *parent = nullptr);
    ~Win();

private slots:
    void on_button1_clicked();

    void on_button2_clicked();

private:
    Ui::Win *ui;
    int index;  //圖片索引

    void paintEvent(QPaintEvent*); //重寫繪圖事件函數,窗口改變或調用update()/repaint()函數會觸發這個事件

};
#endif // WIN_H

cpp文件

#include "win.h"
#include "ui_win.h"

Win::Win(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Win)
{
    ui->setupUi(this);
    index=0;




}

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


void Win::on_button1_clicked()
{
if(--index<0)
    {
    index=4;
    }
update(); //觸發繪圖事件
}

void Win::on_button2_clicked()
{
    if(++index>4)
        {
        index=0;
        }
update();
}

void Win::paintEvent(QPaintEvent*)
{
QPainter painter(this); //創建畫家對象
//參數:繪圖設備--在什么設備上作畫
QRect rect=ui->frame1->frameRect();
QImage image("./tu/"+QString::number(index)+".jpg");
//:  表示加載資源文件
//tu1是前綴,tu是文件夾名
painter.drawImage(rect,image);


}

main文件

#include "win.h"

#include <QApplication>

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

 

以上工程下載地址:鏈接:https://pan.baidu.com/s/1uH3swAJi8IfsMmjseaexKg     提取碼:6666  

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM