Qt控件函数的重写

重写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);
}
参考  http://www.cnblogs.com/hicjiajia/archive/2012/05/30/2526768.html

你可能感兴趣的:(Qt)