Increase the number of small features in the main window of the Widget
1, click the left button to display the "haha" label in the upper left corner, right-click to display the "lala"
In widget.h added:
1 #include <QMouseEvent> 2 protected: 3 void mousePressEvent(QMouseEvent *);
In widget.cpp added:
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, the coordinates of the mouse click point is displayed in the label
Only minor changes to the 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, real-time display coordinates of the mouse position
Modify 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 }
- Line 6 is set to real-time tracking mouse, if not, we should hold the mouse while moving coordinate changes have
- Do not forget to declare mouseMoveEvent in widget.h in ()