Qt 事件或 repaint() 函数不工作

Qt events or repaint() function not working

关键事件侦听器或函数 repaint() 不起作用,我尝试直接调用 paintEvent(QPaintEvent *) 但它也不起作用,感谢进一步的答案。

代码如下:

window.h

#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 对象进行比较。