gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:34:37 24 4
gpt4 key购买 nike

关键事件监听器或函数 repaint() 不工作,我试过直接调用 paintEvent(QPaintEvent *) 但它也没有工作,感谢进一步的回答。

代码如下:

窗口.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

窗口.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();
}

主要.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com