2

I'm building an application that launches an exe file on button press with QProcess. I have multiple buttons that are created in this way:

  • Program reads from local database the information needed to create buttons (name, exe path)
  • Then for each entry in the database it creates a button with the associated name in a previously created QFrame.

How can I associate the respective executable with the button?

Code

QSqlQueryModel query;
query.setQuery("SELECT * FROM games");
if (!query.record(0).isEmpty()) {
    for (int i = 0; i < query.rowCount(); i++) {
        QPushButton* button = new QPushButton(query.record(i).value("name").toString(), ui->frame);
        button->setGeometry(120 * (ui->frame->findChildren<QPushButton*>().size() - 1), 0, 110, 150);
        button->show();
    }
}

Notes: The number of buttons in the frame is random

System Info: I'm on Windows 11, using Qt 6.3.1 MSVC 64-bit

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 1
    https://doc.qt.io/qt-5/qsignalmapper.html is something you should look at I think – Mat Aug 09 '22 at 14:11
  • ***How can I associate the respective executable with the button?*** Probably handle that in a slot that is connected to the buttons clicked signal. Or maybe a lambda connected to the clicked signal. – drescherjm Aug 09 '22 at 14:12

1 Answers1

1

I would use a lmbda like this:

QSqlQueryModel query;
query.setQuery("SELECT * FROM games");
if (!query.record(0).isEmpty()) {
    for (int i = 0; i < query.rowCount(); i++) {
        QPushButton* button = new QPushButton(query.record(i).value("name").toString(), ui->frame);
        button->setGeometry(120 * (ui->frame->findChildren<QPushButton*>().size() - 1), 0, 110, 150);
        connect(button, &QPushButton::clicked, [=] {
          // Insert button specific code inside this lambda
        });
        button->show();
    }
}

From the docs: Qt 6 Signals and Slots

Nathaniel Johnson
  • 4,731
  • 1
  • 42
  • 69