我有一个包含一些数据的表格。但是,由于并非所有信息都适合表格,因此用户应该可以选择通过按此行中的按钮来获取有关该行的更多信息。我目前通过以下方式添加按钮:
int lastRow = table->rowCount();
table->insertRow(lastRow);
QWidget* pWidget = new QWidget();
pWidget->setFixedWidth(30);
LdtButton* btn_help = new LdtButton();
btn_help->addInactiveIcon(QPixmap(":/icons/help_inactive.png"));
btn_help->addHoverIcon(QPixmap(":/icons/help_hovered.png"));
QHBoxLayout* pLayout = new QHBoxLayout(pWidget);
pLayout->addWidget(btn_help);
pLayout->setAlignment(Qt::AlignCenter);
pLayout->setContentsMargins(0, 0, 0, 0);
pWidget->setLayout(pLayout);
table->setCellWidget(lastRow, 1, pWidget);
但是,我真的不知道如何连接这些按钮,因此我在按下按钮时会得到按钮所在的行,因此我可以输出适当的信息。(并非每行都有按钮(
使用信号QPushButton::clicked
和 lambda 调用正确的方法(使用捕获传递行(。
QTableWidget* table = new QTableWidget(0, 2);
QStringList values = {"foo", "bar", "spam"};
for (QString const& value : values)
{
int lastRow = table->rowCount();
table->insertRow(lastRow);
table->setItem(lastRow, 0, new QTableWidgetItem(value));
QWidget* pWidget = new QWidget();
QPushButton* btn_help = new QPushButton("help");
QHBoxLayout* pLayout = new QHBoxLayout(pWidget);
pLayout->addWidget(btn_help);
pLayout->setAlignment(Qt::AlignCenter);
pLayout->setContentsMargins(0, 0, 0, 0);
pWidget->setLayout(pLayout);
table->setCellWidget(lastRow, 1, pWidget);
// Call your method in the lambda
QObject::connect(btn_help, &QPushButton::clicked, [lastRow]() {qDebug() << "Show help for " << lastRow; });
}
table->show();
它将显示:
Show help for 0
Show help for 1
Show help for 2