在焦点上选择 QLineEdit 的文本 [英] Select text of QLineEdit on focus
问题描述
我使用 QtDesigner 创建了一个对话框.对话框中有一个带有一些默认内容的 QLineEdit
对象.当对话框初始化并且焦点转到 QLineEdit
时,我希望自动选择默认内容,因此一旦用户开始编写,之前的内容将被覆盖.
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.
在构造函数中:
dialog->accept();
和
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:
创建一个派生自 QLineEdit
的类并覆盖头部中的 focusInEvent
:
Create a class derived from QLineEdit
and override the focusInEvent
in the header:
virtual void focusInEvent(QFocusEvent *event) override;
然后像这样实现它:
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 ;-)
这篇关于在焦点上选择 QLineEdit 的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!