关键事件侦听器或函数repaint()无法正常工作,我尝试过直接调用paintEvent(QPaintEvent *),但由于进一步的回答,它也无法正常工作。

这是代码:

窗口

#ifndef WINDOW_H
#define WINDOW_H

#include <QWidget>
#include <QPainter>
#include <QPaintEvent>
#include <QRectF>

namespace Ui {
class Window;
}

class Window : public QWidget
{
    Q_OBJECT

public:
    explicit Window(QWidget *parent = 0);
    ~Window();

    void paintEvent(QPaintEvent *);
    void keyPressEvent(QKeyEvent *  );

private:
    Ui::Window *ui;

    QRectF player;

    QPainter * painter = new QPainter(this);
};

#endif // WINDOW_H


window.cpp

#include "window.h"
#include "ui_window.h"

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

    player.setX(0);
    player.setY(0);
    player.setWidth(50);
    player.setHeight(50);
}

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

void Window::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setPen(QPen(Qt::black, 3, Qt::DashDotLine, Qt::RoundCap));
    painter.setBrush(QBrush(Qt::blue));
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.drawEllipse(player.x(), player.y(), player.width(), player.height());
}

void Window::keyPressEvent(QKeyEvent * event)
{
    if(event->type() == Qt::Key_W)
        player.setY(player.y() - 1);
    if(event->type() == Qt::Key_S)
        player.setY(player.y() + 1);
    if(event->type() == Qt::Key_A)
        player.setX(player.x() - 1);
    if(event->type() == Qt::Key_D)
        player.setX(player.x() + 1);
    repaint();
}


main.cpp

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

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

    return a.exec();
}

最佳答案

Window::keyPressEvent中,将event->type()替换为event->key()

另外,看看编译器的输出。我认为应该警告您将QEvent::TypeQt::Key对象进行比较。

关于c++ - Qt事件或repaint()函数不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27931479/

10-11 19:19