I have a QLineEdit
with an input mask, so that some kind of code can easily be entered (or pasted). Since you can place the cursor anywhere in the QLineEdit
even if there is no text (because there is a placeholder from the input mask):
If people are careless and unattentive enough this leads to them typing in the middle of the text box whereas they should start typing at the beginning. I tried the trivial way of ensuring that the cursor is at the start upon focus by installing an event filter:
bool MyWindowPrivate::eventFilter(QObject * object, QEvent * event)
{
if (object == ui.tbFoo && event->type() == QEvent::FocusIn) {
ui.tbFoo->setCursorPosition(0);
}
return false;
}
This works fine with keybaord focus, i.e. when pressing ⇆ or ⇧+⇆, but when clicking with the mouse the cursor always ends up where I clicked. My guess would be that QLineEdit
sets the cursor position upon click itself after it got focus, thereby undoing my position change.
Digging a little deeper, the following events are raised when clicking¹ and thus changing focus, in that order:
FocusIn
MouseButtonPress
MouseButtonRelease
I can't exactly catch mouse clicks in the event filter, so is there a good method of setting the cursor position to start only when the control is being focused (whether by mouse or keyboard)?
¹ Side note: I hate that Qt has no documentation whatsoever about signal/event orders for common scenarios such as this.
QMouseEvent
. – TippetsfocusInEvent
behavior afterwards. What you should do is override thefocusInEvent
as suggested by Dmitry. Here you can see the default behavior. – Panchromatic