自己用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);}}

qt

1个回答

 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);
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问