Qt 中的简单 QImage 动画

问题描述

我想以一种简单的方式(不一定是最有效和/或最优雅的方式)实现以下目标:我想创建一个 320x200 QImage,我会使用 setPixel 命令不断更新它。 QImage 应该显示在屏幕上并在发生变化时更新。例如,可能看起来像这样:

QImage image (320,200,QImage::Format_Indexed8);
while (true) {
    image.setPixel (rand() % 320,rand() % 200,rand() % 16);
    [show updated image]
}

我是否需要有一个事件处理程序等来实现这一点,或者是否有可能在主程序中有这样一个简单的无限循环?

解决方法

应用程序主线程中的无限循环将阻止核心应用程序处理任何 GUI 事件。频繁执行操作的最简单方法是使用 QTimer:

#include <QTimer>

// you can start the timer in your main window constructor
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),ui(new Ui::MainWindow)
{
    // define `image` as a MainWindow member in your .h
    image = QImage(320,200,QImage::Format_Indexed8);
    QTimer *t = new QTimer(this);
    connect(t,SIGNAL(timeout()),this,SLOT(changeImage()));
    t->setInterval(100);  // ex: a 100ms interval
    t->start();
}

void MainWindow::changeImage() {
    image.setPixel (rand() % 320,rand() % 200,rand() % 16);
}

因为你的 .h 看起来像这样:

#include <QImage>

class MainWindow : public QMainWindow
{
    // ...
    private:
       QImage image;
    private slots:
       void changeImage();
}