在主窗口Widget中增加几个小功能
1、点击左键,在左上角label中显示“haha”,点击右键,显示“lala”
在widget.h中添加:
1 #include <QMouseEvent> 2 protected: 3 void mousePressEvent(QMouseEvent *);
在widget.cpp中添加:
1 void Widget::mousePressEvent(QMouseEvent *ev){ 2 if(ev->button()==Qt::LeftButton){ 3 ui->label->setText("haha"); 4 }else if(ev->button()==Qt::RightButton){ 5 ui->label->setText("lala"); 6 } 7 }
2、在label中显示鼠标点击点的坐标
只需对Widget::mousePressEvent()稍作修改:
1 void Widget::mousePressEvent(QMouseEvent *ev){ 2 QPoint point=ev->pos(); 3 if(ev->button()==Qt::LeftButton){ 4 ui->label->setText(QString::asprintf("%d",point.x())); 5 }else if(ev->button()==Qt::RightButton){ 6 ui->label->setText(QString::asprintf("%d",point.y())); 7 } 8 }
3、鼠标位置坐标的实时显示
修改widget.cpp:
1 Widget::Widget(QWidget *parent) : 2 QWidget(parent), 3 ui(new Ui::Widget) 4 { 5 ui->setupUi(this); 6 this->setMouseTracking(true); 7 } 8 9 Widget::~Widget() 10 { 11 delete ui; 12 } 13 14 void Widget::mouseMoveEvent(QMouseEvent *ev){ 15 QPoint point=ev->pos(); 16 ui->label->setText(QString::asprintf("坐标:%d %d",point.x(),point.y())); 17 }
- 第6行是设定实时追踪鼠标,如果不加,就要一边按着鼠标一边动坐标才有变化
- 别忘了在widget.h中声明mouseMoveEvent()