双击LineEdit控件执行一个事件。我们LineEdit正常是单击光标悬浮的这种状态,所以我需要对这个控件进行重写。
因为是要重写,所以我们需要自定义QLineEdit。
Qt 控件重写
/*MyLineEdit.h*/
#ifndef MYLINEEDIT_H
#define MYLINEEDIT_H
#include
#include
class MyLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit MyLineEdit(QWidget *parent = 0);
~MyLineEdit();
protected:
void mouseDoubleClickEvent(QMouseEvent *event);
};
#endif // MYLINEEDIT_H
把你要让这个控件执行的事件放到你重写的这个类中,并实现它。
/*MyLineEdit.cpp*/
#include "mylineedit.h"
#include
#include
MyLineEdit::MyLineEdit(QWidget *parent) :
QLineEdit(parent)
{
}
MyLineEdit::~MyLineEdit()
{
}
void MyLineEdit::mouseDoubleClickEvent(QMouseEvent *event)
{
qDebug()<<"hi~我在执行QLineEdit双击事件~";
}
做完这步就相当于重写完成了,接下来就是需要使用这个自定义的类。
/*from.h*/
#ifndef FORM_H
#define FORM_H
#include
namespace Ui {
class Form;
}
class Form : public QWidget
{
Q_OBJECT
public:
explicit Form(QWidget *parent = 0);
~Form();
private:
Ui::Form *ui;
};
#endif // FORM_H
form.cpp
#include "form.h"
#include "ui_form.h"
#include "mylineedit.h"
Form::Form(QWidget *parent) :
QWidget(parent),
ui(new Ui::Form)
{
ui->setupUi(this);
MyLineEdit* a = new MyLineEdit(this);
ui->verticalLayout->addWidget(a);
}
Form::~Form()
{
delete ui;
}
/*********************重写QLineEdit的focusInEvent()和focusOutEvent()函数:
源码如下:
// MYLINEEDIT_H
#ifndef MYLINEEDIT_H
#define MYLINEEDIT_H
#include
class MyLineEdit : public QLineEdit
{
Q_OBJECT
public:
MyLineEdit(QWidget *parent=0);
~MyLineEdit();
protected:
virtual void focusInEvent(QFocusEvent *e);
virtual void focusOutEvent(QFocusEvent *e);
};
#endif // MYLINEEDIT_H
`
//myLineEdit.cpp
#include "myLineEdit.h"
MyLineEdit::MyLineEdit(QWidget *parent):QLineEdit(parent)
{
}
MyLineEdit::~MyLineEdit()
{
}
void MyLineEdit::focusInEvent(QFocusEvent *e)
{
QPalette p=QPalette();
p.setColor(QPalette::Base,Qt::green); //QPalette::Base 对可编辑输入框有效,还有其他类型,具体的查看文档
setPalette(p);
}
void MyLineEdit::focusOutEvent(QFocusEvent *e)
{
QPalette p1=QPalette();
p1.setColor(QPalette::Base,Qt::white);
setPalette(p1);
}
`
//widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "MyLineEdit.h"
#include
#include
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
init();
}
Widget::~Widget()
{
delete ui;
}
void Widget::init()
{
lineEdit1=new MyLineEdit(this);
lineEdit2=new MyLineEdit(this);
gridLayout=new QGridLayout;
gridLayout->addWidget(lineEdit1,0,0);
gridLayout->addWidget(lineEdit2,1,0);
setLayout(gridLayout);
}