问题描述
- 自己用Qt画了一个方块,想要控制方块移动,paintevent和keypressevent已经写好
-
void Widget::paintEvent(QPaintEvent*event)
{QPainterpainter(this);
painter.setPen(QPen(Qt::black,8));
painter.drawRect(50,50,50,50);}void Widget::keyPressEvent(QKeyEvent*event){
switch(event->key())
{caseQt::Key_S:
move(pos().x(),ui->pushButton->pos().y()-50);break;
caseQt::Key_W:
move(pos().x(),ui->pushButton->pos().y()+50);break;
default:QWidget::keyPressEvent(event);}}
解决方案
int xx = 0;
int yy = 0;
void QtTest::paintEvent(QPaintEvent*event)
{
QPainter painter(this);
painter.setPen(QPen(Qt::black,1));
painter.drawRect(50+xx,50+yy,50,50);
}
void QtTest::keyPressEvent(QKeyEvent*event)
{
switch(event->key())
{
case Qt::Key_A:
xx--;break;
case Qt::Key_D:
xx++;break;
case Qt::Key_W:
yy--;break;
case Qt::Key_S:
yy++;break;
}
repaint ();
QWidget::keyPressEvent(event);
}
时间: 2024-09-30 17:56:19