user3026053 user3026053 - 19 days ago 6
C++ Question

How do you connect paintEvent to a slot?

Just like the title says I want to connect

paintEvent
to a slot, so that it can be triggered by a timer, how do I do this? I can provide any more information you guys need, I'm very new to QT though, so keep that in mind.

EDIT: So I tried it in a little test program and it doesn't appear to be updating. Unless I've misunderstood how
paintEvent
works, I don't know what's wrong. This should move a black point (10x10 pixels) across the screen from the upper left corner to the bottom right.

Here's the header file:

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QtGui>
#include <QtCore>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
Q_OBJECT

public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
QTimer *timer;

private:
Ui::Dialog *ui;

protected:
void paintEvent(QPaintEvent *e);

};

#endif // DIALOG_H


Here's the implementation file:

#include "dialog.h"
#include "ui_dialog.h"
#include "windows.h"

Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);

timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(update()));

timer->start(1000);
}

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

void Dialog::paintEvent(QPaintEvent *e)
{
QPainter painter(this);
QPen pointPen(Qt::black);
pointPen.setWidth(10);
painter.setPen(pointPen);
QPoint test;

static unsigned int coord;

coord = 10;

test.setX(coord);
test.setY(coord);

painter.drawPoint(test);

coord += 10;


}

Here's the client code:

#include "dialog.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();

return a.exec();
}

Answer

You cannot connect to paintEvent directly, since it is not a slot. Instead, connect your timer signal to repaint (to trigger an immediate repaint) or update (the preferred method, since it consolidates multiple repaint requests to avoid flicker).

EDIT

There's some quirkiness regarding updating a QDialog (see this thread on the Qt forums) -- apparently, due to a bug in Qt versions 4.6 and below (and possibly in later versions, as well).

I would refrain from overriding paintEvent on a QDialog. Instead, create a custom QWidget (which you can insert as a child into your dialog) and perform your rendering there.

Comments