简体   繁体   中英

How to enter a character to QLineEdits from QPushButtons depending on the focus in Qt

I am using Qt Creator to make a UI.
UI consists of two or more QLineEdit s and ten QPushButton s to input 0-9 numberic characters to QLineEdit s. How can I enter 0-9 number string s in both QLineEdit s one by one.

If I press QPushButton with label '5'and cursor is on QLineEdit (say QLineEdit 1) it should append '5' in QLineEdit 1 or if QLineEdit 2 is selected it should append '5' in QLineEdit 2 and respectively with the other QPushButton s also.

you could have a slot in your ui class like the following

void MyDialog::numberButtonPressed()
{
    QPushButton* btn = qobject_cast<QPushButton*>(QObject::sender());
    if (!btn)
        return; // TODO error handling
    ui.lineEdit->setText(ui.lineEdit->text() + btn->text());
}

and then QObject::connect all numeric buttons to that slot .

cheers

In QT Creator after adding pushbutton to slots in UI, go to function and check if it has focus or not with hasFocus().

eg

void MainWindow::on_pushButton_clicked()
{
    if(ui->lineEdit_1->hasFocus)
    {
        ui->lineEdit_1->setText("your text");
    }
    else if(ui->lineEdit_2->hasFocus)
    {
        ui->lineEdit_2->setText("your text");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM