这种生成的多个按钮,怎么根据这个按钮文本上对应的i来设置不同的槽函数,输出不同的i啊

这种生成的多个按钮,怎么根据这个按钮文本上对应的i来设置不同的槽函数,输出不同的i啊

关注【以下回答由 GPT 生成】
优化后的问题:
问题标题: 如何根据生成的按钮文本设置不同的槽函数并输出不同的值? 问题标签: qt 问题内容: 我有一个程序生成了多个按钮,并且每个按钮上都有一个对应的文本。我想根据这些按钮文本的不同来设置不同的槽函数,并且希望每个槽函数能输出对应按钮的值。以下是生成按钮的代码:
QPushButton* button[100000];
int i = 0;
while (p != NULL) {
QLabel* label = new QLabel(p->get_name().c_str());
scrollLayout->addWidget(label);
QLabel* label2 = new QLabel(p->get_image());
scrollLayout->addWidget(label2);
button[i] = new QPushButton("查找具体信息: " + QString::number(i));
scrollLayout->addWidget(button[i]);
i++;
p = p->next;
}
请问应该如何设置按钮的槽函数,以便根据按钮的文本输出不同的值?
回答:
以下是代码示例:
QPushButton* button[100000];
int i = 0;
while (p != NULL) {
QLabel* label = new QLabel(p->get_name().c_str());
scrollLayout->addWidget(label);
QLabel* label2 = new QLabel(p->get_image());
scrollLayout->addWidget(label2);
button[i] = new QPushButton("查找具体信息: " + QString::number(i));
scrollLayout->addWidget(button[i]);
// 使用Lambda表达式设置按钮的槽函数
QObject::connect(button[i], &QPushButton::clicked, [i]() {
// 根据按钮的文本获取对应的值
QString buttonText = button[i]->text();
QString value = buttonText.mid(buttonText.indexOf(":") + 2);
// 输出对应按钮的值
qDebug() << "按钮" << i << "的值是:" << value;
});
i++;
p = p->next;
}
以上代码中,通过使用Lambda表达式来设置按钮的槽函数,并通过在槽函数内部根据按钮的文本获取对应的值,然后进行输出,实现了根据按钮的文本输出不同的值的功能。