chenxiao_huan
2015-08-06 13:04
采纳率: 100%
浏览 2.8k
已采纳

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • wafstudio 2015-08-06 14:24
    已采纳
     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);
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题