问题
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