开发者

Select text of QLineEdit on focus

开发者 https://www.devze.com 2023-01-10 21: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 th

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() ) );


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:

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 ;-)


Call

lineEdit->selectAll();

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


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.


You can use QApplication::focusChanged along with QTimer::singleShot to select all the text on a changed focus.

Normally your QApplication is declared in main, so use QObject::connect there, eg:

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    My_Main_Window w();
    QObject::connect(&a, SIGNAL(focusChanged(QWidget*, QWidget*)),
                     &w, SLOT(my_focus_changed_slot(QWidget*, QWidget*)));
    w.show();

    return a.exec();
}

Remember to make the public slot in the My_Main_Window class:

public slots:
void my_focus_changed_slot(QWidget*, QWidget*);

Then in your definition of my_focus_changed_slot, check if the second QWidget* (which points to the newly focused widget) is the same as the QLineEdit you wish to select all of, and do so using QTimer::singleShot so that the event loop gets called, then the QLineEdit has the selectAll slot called immediately after, eg

void My_Main_Window::focus_changed(QWidget*, QWidget* new_widget) {
    if (new_widget == my_lineedit) {
        QTimer::singleShot(0, my_lineedit, &QLineEdit::selectAll);
    }
}

where my_lineedit is a pointer to a QLineEdit and is part of the My_Main_Window class.

0

精彩评论

暂无评论...
验证码 换一张
取 消