Qt實現(xiàn)編輯框失去焦點隱藏功能
今天來為大家分享一個小功能,首先看實現(xiàn)的效果吧~
功能講解:
QLineEdit控件進行文本編輯,點擊保存按鈕后,隱藏編輯框和保存按鈕,僅展示編輯內(nèi)容,當鼠標點擊空白處時,同樣隱藏編輯框、隱藏保存按鈕,但不存儲編輯文本
如果你要需要實現(xiàn)這樣的功能,就繼續(xù)往下看吧~
1.控件
三個控件:QLineEdit編輯框、QPushButton按鈕、QLabel純文本展示。
默認QLabel控件是隱藏狀態(tài),只有點擊保存按鈕以及失去焦點后才會展示。
2.響應消息
此時需要響應兩個消息。
消息1:點擊保存按鈕
connect(ui.btnSave, &QPushButton::clicked, this, &QMyWidget::OnBnClickedSave);
消息2:QLineEdit控件失去焦點后操作
對于控件來說,失去焦點的一般是focusOut消息,在QLineEdit這個類中,該消息是受保護的,那么如果要獲取控件是如何失去焦點的,只能繼承QLineEdit類,將失去焦點的消息,發(fā)送給調(diào)用者。
.h聲明
class CustomLineEdit : public QLineEdit { Q_OBJECT public: CustomLineEdit(QWidget *parent); ~CustomLineEdit(); signals: void Msg_SendCustomLineEditFocusOut(); //失去焦點消息 protected: void focusOutEvent(QFocusEvent *event) override; };
.cpp實現(xiàn)
CustomLineEdit::CustomLineEdit(QWidget *parent) : QLineEdit(parent) { } CustomLineEdit::~CustomLineEdit() { } void CustomLineEdit::focusOutEvent(QFocusEvent *event) { emit Msg_SendCustomLineEditFocusOut(); QLineEdit::focusOutEvent(event); }
3.窗口功能實現(xiàn)
3.1雙擊響應QLabel控件
在Qt控件中,QLabel是不會響應鼠標按下消息,之前文章中就有提到,如何讓QLabel控件響應消息 Qt|控件點擊消息獲取方法,這篇文章中詳細講述了如何讓QLabel控件響應鼠標按下消息。
鼠標雙擊QLabel控件功能:雙擊后隱藏QLabel控件,并將QLineEdit編輯框控件、QPushButton保存控件展示出來。
//雙擊標題事件
if (event->type() == QEvent::MouseButtonDblClick) { //此刻,響應雙擊消息后,隱藏該控件,顯示編輯框、和保存按鈕 m_labTitle->hide(); m_editTitle->show(); m_editTitle->clear(); m_btnSave->show(); }
3.2QLineEdit失去焦點
編輯框失去焦點后功能:顯示QLabel控件,隱藏QLineEdit控件并且不記錄編輯的內(nèi)容,并隱藏保存按鈕。
m_labTitle->show(); m_editTitle->hide(); m_btnSave->hide();
3.3QPushButton保存按鈕
點擊保存按鈕后功能:獲取QLineEdit編輯框內(nèi)的文本并隱藏、隱藏保存按鈕,顯示QLbable控件,靜態(tài)文本展示。
QString qTitle = m_editTitle->text(); m_labTitle->setText(qTitle); //標題文本設(shè)置 m_labTitle->show(); m_editTitle->hide(); m_btnSave->hide();
實現(xiàn)了QLineEdit編輯框的失去焦點消息,那么該消息是什么時候觸發(fā)呢?
例如,點擊保存按鈕時,先響應保存按鈕,后響應鼠標失去焦點消息。
到此這篇關(guān)于Qt實現(xiàn)編輯框失去焦點隱藏功能的文章就介紹到這了,更多相關(guān)Qt編輯框失去焦點隱藏內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
typedef_struct與struct之間的區(qū)別
本篇文章主要是對typedef struct與struct之間的區(qū)別進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12