How can i get current focused QLineEdit in qt?

人盡茶涼 提交于 2019-12-23 18:27:12

问题


How can I identify which QLineEdit has the current focus in qt?

To set the focus for QLinEdit I have tried:

   ui->linedit->setfocus();

but it also not working for me. How can I solve these two?


回答1:


To identify which focused Widget (QlineEdit or any QWidget), you need to get all your current widget children, cast each to QLineEdit, and check which one has focus, sample code:

QList<QWidget*> mylineEdits = this->findChildren<QWidget*>();
QListIterator<QWidget*> it(mylineEdits); // iterate through the list of widgets
QWidget *lineEditField;
while (it.hasNext()) {
    lineEditField = it.next(); // take each widget in the list
    if(QLineEdit *lineE = qobject_cast<QLineEdit*>(lineEditField)) {  // check if iterated widget is of type QLineEdit
        //
        if (lineE->hasFocus())
          {
            // this has the focus ...   
          }

    }
}

Second issue, setting focus on QWidget, already answered in this Post:




回答2:


Set focus to a widget with setFocus() function.

ui->lineEdit_3->setFocus();

You can check focus on a widget using hasFocus() function.

QWidget * widgetName = qApp->focusWidget();
qDebug () << widgetName->objectName();

output: "lineEdit_3"

When the focused widget is changed QApplication::focusChanged(QWidget *old, QWidget *now) signal is emitted.You can connect it to a slot in which you do what ever you like based on the focus change.



来源:https://stackoverflow.com/questions/46702487/how-can-i-get-current-focused-qlineedit-in-qt

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