c++ - 如何将 paintEvent 连接到插槽?

标签 c++ qt

正如标题所说,我想将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/

相关文章:

linux - 在linux上部署一个Qt项目

c++ - C++将函数调用列表作为参数传递

c++ - 配置类也使用继承时的继承

c++ - 如何从排序的 vector 中有效地删除一个值?

c++ - 如何解决以下错误?

linux - 哪个交叉编译器?

c++ - 如何为 Qt 应用程序创建可执行文件?

c++ - 如何共享我的 C/C++ 项目并隐藏部分源代码?

c++ - 标识符 "a"在 C++ 中未定义

c++ - QLabel “break”单词如果太长