(QT study notes): Commonly used mouse events

Common mouse events

Method to realize

  • Step 1, drag a TextLab control

  • Since these mouse events are virtual functions and protected, they need to be rewritten.
  • But the QLabel source code cannot be defined at this time, we can inherit QLabel and then rewrite it .
  • Step 2, right-click the project to add C++ class

  • Step 3, modify the file corresponding to MyLabel (we want to rewrite QLabel, but without this option inheritance, only QWidget can be inherited)

  • Step 4, copy the name of MyLabel, open the ui file created in step 1, select the TextLab control, and right-click to promote it to

  • Step 5. In the MyLabel header file, declare to rewrite the mouse event
//鼠标进入事件
void enterEvent(QEvent *);

//鼠标离开事件
void leaveEvent(QEvent *);

//鼠标按下事件
void mousePressEvent(QMouseEvent *ev);

//鼠标释放事件
void mouseReleaseEvent(QMouseEvent *ev);

//鼠标移动事件
void mouseMoveEvent(QMouseEvent *ev);
  • In the MyLabel source file
//鼠标进入事件
void MyLabel::enterEvent(QEvent *)
{
   qDebug() << "鼠标进入了";
}

//鼠标离开事件
void MyLabel::leaveEvent(QEvent *)
{
  qDebug() << "鼠标离开了";
}
//鼠标按下事件
void MyLabel::mousePressEvent(QMouseEvent *ev)
{

    //鼠标左键按下  打印信息
      if(ev->button() == Qt::LeftButton)
      {
        QString str =  QString("鼠标按下了 x =  %1  y = %2 " ).arg(ev->x()).arg(ev->y());
        qDebug() << str;
     }
}
//鼠标释放事件
void MyLabel::mouseReleaseEvent(QMouseEvent *ev)
{

    if(ev->button() == Qt::LeftButton)
    {
        QString str =  QString("鼠标释放了 x =  %1  y = %2 " ).arg(ev->x()).arg(ev->y());
        qDebug() << str;
    }
}
//鼠标移动事件
void MyLabel::mouseMoveEvent(QMouseEvent *ev)
{
     if(ev->buttons() & Qt::LeftButton)
     {
        QString str =  QString("鼠标移动了 x =  %1  y = %2 " ).arg(ev->x()).arg(ev->y());
        qDebug() <<str;
     }
}

 

Guess you like

Origin blog.csdn.net/baidu_41388533/article/details/111566857