How to make QPushButtons to add text into QLineEdit box?

user569474 picture user569474 · Nov 29, 2011 · Viewed 13.9k times · Source

I used Qt Creator to make a "keyboard" window with sixty QPushButtons and one QLineEdit. How can I make the buttons to add characters into QLineEdit text box? If I press a QPushButton with the label 'Q' on it, I want the program to add the Unicode character 'Q' on the text box.

Answer

sdb picture sdb · Nov 29, 2011

One way to do this would be to just connect the 'clicked' signal from all the buttons to a slot, and then handle the adding of the character there.

For example, if the all keyboard buttons are inside a layout called 'buttonLayout', in your MainWindow constructor you can do this:

for (int i = 0; i < ui->buttonLayout->count(); ++i)
{
    QWidget* widget = ui->buttonLayout->itemAt( i )->widget();
    QPushButton* button = qobject_cast<QPushButton*>( widget );

    if ( button )
    {
        connect( button, SIGNAL(clicked()), this, SLOT(keyboardButtonPressed()) );
    }
}

Then in the slot implementation, you can use QObject::sender(), which returns the object that sent the signal:

void MainWindow::keyboardButtonPressed()
{
    QPushButton* button = qobject_cast<QPushButton*>( sender() );

    if ( button )
    {
        ui->lineEdit->insert( button->text() );
    }
}