Enter causes cursor movement like in Tab Order
Hello,
In a dialog there are some edit fields e.g. QLineEdit. It is possible to set the Tab order, so that the cursor moves from one field to another when the Tab button is pressed.
Is it possible to achieve the same effect, when the return button is pressed?
Thx for your hints
Re: Enter causes cursor movement like in Tab Order
For the first question the answer is
"use QWidget::setTabOrder" or Designer
For the second you have to reimplement the QWidget::keyPressEvent and customize the default behaviour in case of Qt::Key_Enter or Qt::Key_Return
for example
Code:
{
switch (e->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
{
if (w == ui->lineEdit) {
next = ui->lineEdit_2;
}
else if (w == ui->lineEdit_2) {
next = ui->lineEdit_3;
}
else if (w == ui->lineEdit_3) {
next = ui->buttonBox;
}
if (next)
next->setFocus();
}
break;
default:
}
}
Re: Enter causes cursor movement like in Tab Order
Quote:
Originally Posted by
mcosta
For the first question the answer is
"use
QWidget::setTabOrder" or Designer
For the second you have to reimplement the
QWidget::keyPressEvent and customize the default behaviour in case of Qt::Key_Enter or Qt::Key_Return
for example
Code:
{
switch (e->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
{
if (w == ui->lineEdit) {
next = ui->lineEdit_2;
}
else if (w == ui->lineEdit_2) {
next = ui->lineEdit_3;
}
else if (w == ui->lineEdit_3) {
next = ui->buttonBox;
}
if (next)
next->setFocus();
}
break;
default:
}
}
Thank you for the answer, but I am afraid it's not that easy with the keyPressEvent.
What about disabled fields (in different combinations)? The setTabOrder solves this automatically.
Of course I can imagine how to solve this, but I am looking for a QT mechanism that helps to fix such an issue.
Re: Enter causes cursor movement like in Tab Order
As an alternate solution, you can capture the KeyPressEvent, either using the above method or using a event filter and send a tab key event to the parent widget (i.e. converting a enter key event on a widget into a tab key event on the parent widget). This solution will respect the tab order, and is scalable solution, i.e. will work even if you changed tab order, or add more widgets in future.
As always, there are many ways to do a given job :)
Re: Enter causes cursor movement like in Tab Order
You can also use QWidget::focusNextPrevChild like
Code:
{
switch (e->key ()) {
case Qt::Key_Return:
case Qt::Key_Enter:
focusNextPrevChild (true);
break;
default:
}
}
or
Code:
{
switch (e->key ()) {
case Qt::Key_Return:
case Qt::Key_Enter:
{
qApp->postEvent (this, newEvent, 0);
}
break;
default:
}
}