Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make QPushButtons to add text into QLineEdit box?

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.

like image 208
user569474 Avatar asked Jan 19 '23 04:01

user569474


2 Answers

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() );
    }
}
like image 88
sdb Avatar answered Jan 30 '23 07:01

sdb


OPTION 1 - Multiple signals and slots

Connect all pushbuttons clicked() signal to a slot

// Let button01 be the A 
connect(ui->button01, SIGNAL(clicked()), this, SLOT(buttonClicked()));
...
// Let button 60 be the Q
connect(ui->button60, SIGNAL(clicked()), this, SLOT(buttonClicked()));

In the buttonClicked() slot you have to figure out which button was clicked and append the corresponding letter to the line edit.

void buttonClicked()
{
    QObject* callingButton = QObject::sender();
    if (callingButton == button01)
        ui->lineEdit->setText(ui->lineEdit->text()+ "A");
    ...
    else if (callingButton == button60)
        ui->lineEdit->setText(ui->lineEdit->text()+ "Q");
}

OPTION 2 - Subclass QPushButton

You could subclass QPushButton in order to avoid the multiple ifs. In your subclass just catch the mouse release event and emit a new signal which will contain the button's text

void KeyboardButton::mouseReleaseEvent(QMouseEvent* event)
{
   emit clicked(buttonLetter); // Where button letter a variable of every item of your subclass
}

Similarly connect the clicked(QString) signal with a slot

connect(ui->button01, SIGNAL(clicked(QString)), this, SLOT(buttonClicked(QString)));
...
connect(ui->button60, SIGNAL(clicked(QString)), this, SLOT(buttonClicked(QString)));

void buttonClicked(QString t)
{
    ui->lineEdit->setText(ui->lineEdit->text()+ t);
}
like image 38
pnezis Avatar answered Jan 30 '23 08:01

pnezis