Qt Focus event, FocusInEvent() and FocusOutEvent()

Posted by the elegant on Sat, 15 Feb 2020 16:46:40 +0100

Description:

At the beginning, I want to realize that there are multiple editable controls (such as QLineEdit, QTextEdit, etc.) on a form. When which control gets the focus, the background of which control will be highlighted to prompt. I found out that the document should use focusInEvent() and focusOutEvent(). In the actual process, I made a very serious mistake. At the beginning, I was here What to do: I rewrite these two functions of the form QWidget, and then pass the QFocusEvent event to the QLineEdit control on the form in the function body:

void Widget::focusInEvent(QFocusEvent *event)
{
      QLineEdit::focusInEvent(event);
       .....
}

When compiling, an error is reported, saying that there is no calling object or anything. Later, I asked the following friend to get the perfect answer:

Since we want the control to get focus change action, we should rewrite focusInEvent() and focusOutEvent(), that is, rewrite qlinedit class, redefine these two processing functions, and then in the main program, include our own rewritten QLineEdit header file. The specific code is as follows:

// MYLINEEDIT_H
#ifndef MYLINEEDIT_H
#define MYLINEEDIT_H
#include <QLineEdit>
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 is valid for the editable input box. There are other types to view documents
       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 <QGridLayout>
#include <QMessageBox>
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);
}

Topics: Qt