QLineEdit添加鼠标点击事件主要分为三步:
重写lineEdit类(MyLineEdit)添加相应的启动的信号和槽的事件将使用时的QLineEdit提升为自己写的类
重写lineEdit类
其中mylineedit.h
#ifndef MYLINEEDIT_H#define MYLINEEDIT_H#include <QLineEdit>#include<QMouseEvent>class MyLineEdit:public QLineEdit//添加mylineedit类继承QLineEdit{Q_OBJECTpublic:explicit MyLineEdit(QWidget *parent = 0);~MyLineEdit();protected://添加并重写鼠标点击事件函数virtual void mousePressEvent(QMouseEvent *e);signals://点击信号函数void clicked(); };#endif // MYLINEEDIT_H
mylineedit.cpp
#include "mylineedit.h"MyLineEdit::MyLineEdit(QWidget *parent):QLineEdit(parent){}MyLineEdit::~MyLineEdit(){}//重写mousePressEvent事件,检测事件类型是不是点击了鼠标左键void MyLineEdit::mousePressEvent(QMouseEvent *e) {//如果单击了就触发clicked信号if (e->button() == Qt::LeftButton) {//触发clicked信号emit clicked();}//将该事件传给父类处理// QLineEdit::mousePressEvent(e);}
如果出现无法解析的错误,应注意将QObject加上
类提升为MyLineEdit
点击控件右击“”提升为“”,添加提升的类即可