FocusInEvent()與FocusOutEvent()


[2010年07月27日文檔]

描述:一開始我要實現的目的就是,在一個窗體上有多個可編輯控件(比如QLineEdit、QTextEdit等),當哪個控件獲得焦點,哪個控件的背景就高亮用來起提示作用,查了下文檔應該用focusInEvent()和focusOutEvent(), 在實際過程中,我犯了十分嚴重的錯誤,最開始的時候我是這樣做的:我重寫了窗體QWidget的這兩個函數,然后再在函數體中把QFocusEvent事件傳遞給窗體上的QLineEdit控件:

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

編譯的時候報錯,說是沒有調用對象什么的,后來問了下朋友才得到了完美的答案:

既然是要控件得到焦點改變動作,則應該重寫該控件的focusInEvent()和focusOutEvent(),即重寫QLineEdit類,再重新定義這兩個處理函數,然后再在主程序中,include 我們自己重寫的QLineEdit頭文件,具體代碼如下:

// 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 對可編輯輸入框有效,還有其他類型,具體的查看文檔
       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);
}

上圖為程序范例,當某個文本框獲得焦點后背景自動填充為綠色,失去焦點后背景恢復白色,這樣就達到了我想要的焦點高亮背景提醒功能,但是實際分析想來還是很復雜的,假如我的程序還有QTextEdit、QSpinBox等等控件,那我還要全部都重寫這些類,麻煩…我原本以為Qt提供了這種獲得與失去焦點的信號,可惜沒有,期待以后版本加上,就更加方便了…


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM