I would like to achieve the following in a simple (not necessarily most efficient and/or elegant way): I want to create a 320x200 QImage that I keep updating with setPixel commands. The QImage should be shown on screen and updated whenever something has changed. The could could for example look like this:
QImage image (320, 200, QImage::Format_Indexed8);
while (true) {
image.setPixel (rand() % 320, rand() % 200, rand() % 16);
[show updated image]
}
Do I need to have an event handler etc. to realize this, or is it possible to just have such a simple endless loop in the main program?
A infinite loop in your application's main thread will block the core application to process any GUI events. The simplest way to perform the operation frequently is to use a 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);
}
As your.h would look like this:
#include <QImage>
class MainWindow : public QMainWindow
{
// ...
private:
QImage image;
private slots:
void changeImage();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.