Select text of QLineEdit on focus

白昼怎懂夜的黑 提交于 2019-12-10 12:42:27

问题


I have created a dialog using QtDesigner. There is a QLineEdit object in the dialog with some default content. When the dialog initializes and the focus goes to the QLineEdit, I want the default content to be auto selected, so once the user start writing, the previous content will be overwritten.

EDIT:

In constructor:

dialog->accept(); 

and

connect( dialog, SIGNAL(accepted()), QlineObj, SLOT( selectAll() ) );

回答1:


Call

lineEdit->selectAll();

after you set the default text. (In the dialog constructor, perhaps.)




回答2:


There is a simpler method to get almost the same behaviour, which is to set the default content using setPlaceholderText() instead of setText(). This will show the default content grayed out and as soon as the QLineEdit gains focus, it will disappear.




回答3:


This is an older question, but nevertheless, I ended up here searching for a solution this exact problem. It can be solved in the following way:

Create a class derived from QLineEdit and override the focusInEvent in the header:

virtual void focusInEvent(QFocusEvent *event) override;

Then implement it like so:

void MyLineEdit::focusInEvent(QFocusEvent *event)
{
    // First let the base class process the event
    QLineEdit::focusInEvent(event);
    // Then select the text by a single shot timer, so that everything will
    // be processed before (calling selectAll() directly won't work)
    QTimer::singleShot(0, this, &QLineEdit::selectAll);
}

Just in case anybody else wonders how this can be done ;-)



来源:https://stackoverflow.com/questions/3434174/select-text-of-qlineedit-on-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!