正如标题所说,我想将paintEvent
连接到一个插槽,以便它可以被定时器触发,我该怎么做?我可以提供你们需要的任何更多信息,不过我对 QT 还很陌生,所以请记住这一点。
编辑:所以我在一个小测试程序中尝试了它,但它似乎没有更新。除非我误解了 paintEvent
的工作原理,否则我不知道哪里出了问题。这应该在屏幕上从左上角到右下角移动一个黑点(10x10 像素)。
这是头文件:
#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
这是实现文件:
#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;
这是客户端代码:
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}
最佳答案
您不能直接连接到 paintEvent
,因为它不是插槽。相反,将您的计时器信号连接到 repaint
(触发立即重绘)或 update
(首选方法,因为它整合了多个重绘请求以避免闪烁)。
编辑
关于更新 QDialog
(参见 this thread on the Qt forums)有一些奇怪的地方——显然,这是由于 Qt 4.6 及以下版本(也可能是更高版本)中的错误。
我会避免覆盖 QDialog
上的 paintEvent
。相反,创建一个自定义的 QWidget
(您可以将其作为子项插入到您的对话框中)并在那里执行渲染。
关于c++ - 如何将 paintEvent 连接到插槽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21652063/