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
CodePudding user response:
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