chenxiao_huan
chenxiao_huan
采纳率100%
2015-08-06 13:04

自己用Qt画了一个方块,想要控制方块移动,paintevent和keypressevent已经写好

  • qt
已采纳

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 wafstudio 6年前
     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);
    }
    
    点赞 2 评论 复制链接分享