revised lineEdit

难点:click时产生QFocusEvent和MousePressEvent,然后MousePressEvent的处理在focusInEvent之后,所以即便将focuseInEvent重载后,mouse event还是会将光标置到点击的位置,而不是选定全部。这时首先判断是否因为mouse focus造成的,如是的话,由重新发送一个由tab引发的focus in(默认的tab引起的focus是全部选定)。这样就ok了。
Purpose: when the first time of clicking the line edit widget, the whole text will be selected, other than the default action, which would insert the cursor in a certain position in the line edit.
Solution: override the focusInEvent virtual method.
Points to be specially addressed:  In a normal way, when the focus changed by the mouse clicking, the default action includes (1) invoking focusIn event which in turn calls the focusInEvent, and (2) normal mouse event which inserts the cursor into a proper position. This will bring a problem, whatever you set the focusInEvent event (for ex., call selectionAll to select all the text) , the normal mouse event will move the cursor to a certain position. A workaround is listing as following:  first check the reason causing the focus change, if it’s due to mouse click, then post in the event queue a tab focus event which by defaut will select all the text in a line edit widget.  
void PmFocusHandledLineEdit::focusInEvent( QFocusEvent * event )
  if (event->reason()==Qt::MouseFocusReason)
    QFocusEvent *fe=new QFocusEvent(QEvent::FocusIn, Qt::TabFocusReason);
    QApplication::postEvent(this, fe);

Leave a Reply

Your email address will not be published. Required fields are marked *