我有一张桌子,上面有一些数据。但是,由于并非所有信息都适合该表,因此用户应该可以选择通过按此行中的按钮来获取该行的更多信息。我目前以以下方式添加按钮:
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);
但是我真的不知道如何连接这些按钮,所以我得到了按钮被按下时所在的行,因此我可以输出适当的信息。 (并非每一行都有一个按钮)
答案 0 :(得分:1)
使用信号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