簡體   English   中英

將QLineEdit焦點設置在Qt中

[英]Set QLineEdit focus in Qt

我有一個qt問題。 我希望QLineEdit小部件在應用程序啟動時具有焦點。 以下面的代碼為例:

#include <QtGui/QApplication>
#include <QtGui/QHBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QLineEdit>
#include <QtGui/QFont>


 int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);

     QWidget *window = new QWidget();
     window->setWindowIcon(QIcon("qtest16.ico"));
     window->setWindowTitle("QtTest");

     QHBoxLayout *layout = new QHBoxLayout(window);

     // Add some widgets.
     QLineEdit *line = new QLineEdit();

     QPushButton *hello = new QPushButton(window);
     hello->setText("Select all");
     hello->resize(150, 25);
     hello->setFont(QFont("Droid Sans Mono", 12, QFont::Normal));

     // Add the widgets to the layout.
     layout->addWidget(line);
     layout->addWidget(hello);

     line->setFocus();

     QObject::connect(hello, SIGNAL(clicked()), line, SLOT(selectAll()));
     QObject::connect(line, SIGNAL(returnPressed()), line, SLOT(selectAll()));

     window->show();
     return app.exec();
 }

為什么line->setFocus()只在布局窗口小部件后放置並在它不工作之前使用時才將焦點設置在行窗口小部件@app啟動上?

可能singleshot另一個技巧是使用singleshot計時器:

QTimer::singleShot(0, line, SLOT(setFocus()));

實際上,這會在事件系統“空閑”之后立即調用QLineEdit實例的setFocus()槽,即在完全構造窗口小部件之后的某個時間。

鍵盤焦點與小部件選項卡順序相關,默認的Tab鍵順序基於小部件的構造順序 因此,創建更多小部件會更改鍵盤焦點。 這就是你必須最后調用QWidget::setFocus

我會考慮在主窗口中使用QWidget的子類來覆蓋showEvent虛函數,然后將鍵盤焦點設置為lineEdit 這將具有在顯示窗口時始終給予lineEdit焦點的效果。

也許這是一個更新,因為最后一個答案是在2012年,OP最后在2014年編輯了這個問題。我這樣做的方式是改變政策,然后設定焦點。

line->setFocusPolicy(Qt::StrongFocus);
line->setFocus();

在Qt中,setFocus()是一個插槽,您可以嘗試其他重載方法,該方法采用Qt :: FocusReason參數,如下所示:

line->setFocus(Qt::OtherFocusReason);

您可以在以下鏈接中閱讀有關焦點原因選項的信息:

http://doc.trolltech.com/4.4/qt.html#FocusReason-enum

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM