I would like to have a QLineEdit
that shows the clearbutton
only when the mouse is over the QLineEdit
(and of course the field is not empty).
I've captured the enter- and leave- events which set the property respectively. This works fine with the exception that it needs an initial enter and leave of the QLineEdit
manually with the mouse. How can I initiate the QLineEdit
correctly, so that it works fine from the beginning?
Trying to simulate the initial mouse movements did not have the expecting results.
cmplLineEdit.h
class cmplLineEdit : public QLineEdit {
Q_OBJECT
public:
explicit cmplLineEdit( QWidget* a_par = 0);
~cmplLineEdit();
private:
void enterEvent( QEvent* a_ev);
void leaveEvent( QEvent* a_ev);
void enableClearButton( bool a_set, int a_del = 0);
private slots:
void initialize( void);
};
cmplLineEdit.cpp
cmplLineEdit::cmplLineEdit( QWidget* a_par) : QLineEdit( a_par) {
m_completeIt = a_cmpl;
setClearButtonEnabled( false);
setFocusPolicy( Qt::StrongFocus);
QTimer::singleShot( 0, this, [=]( void) { initialize(); });
}
cmplLineEdit::~cmplLineEdit() {
}
bool cmplLineEdit::cursorIsInField() {
return rect().contains( mapFromGlobal( QCursor::pos()));
}
void cmplLineEdit::initialize( void) {
QApplication::postEvent( this, new QEvent( ! cursorIsInField() ? QEvent::Enter : QEvent::Leave));
QApplication::postEvent( this, new QEvent( cursorIsInField() ? QEvent::Enter : QEvent::Leave));
}
void cmplLineEdit::enableClearButton( bool a_set, int a_del) {
if( a_del < 0) {
setClearButtonEnabled( a_set);
} else
QTimer::singleShot( a_del, this, [=]( void) { setClearButtonEnabled( a_set); });
}
void cmplLineEdit::enterEvent( QEvent* a_ev) {
enableClearButton( true, 0);
}
void cmplLineEdit::leaveEvent( QEvent* a_ev) {
enableClearButton( false, 0);
}
Yes, mouse tracking is on (otherwise I wouldn' get the enter- and leave-events). I rewrote the code, implementing
setClearButtonEnabled()
by myself. Now it's working. For anybody who is interested:cmplEdit.h:
cmplEdit.cpp: