Search code examples
c++user-interfaceqt4qlineeditqpushbutton

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 QLineEdits and ten QPushButtons to input 0-9 numberic characters to QLineEdits. How can I enter 0-9 number strings in both QLineEdits 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 QPushButtons also.


Solution

  • 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