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