QTableWidget中添加QPushbutton,需要三步:
1.新建一个按钮控件,调用QTableWidget中的接口setCellWidget()插入按钮;
2.绑定按钮点击时触发的槽函数,并根据要求实现相关功能;
3.使用QPushButton* pSenderObj = qobject_cast<QPushButton*>(sender())获取当前QTableWidget点击的按钮;
具体过程参见下面的代码:
// 新建一个按钮
QPushButton* pTestBtn = new QPushButton(tr("Report"), this);
// 绑定槽函数
connect(pReportBtn, SIGNAL(clicked()), this, SLOT(slotReportBtnClicked()));
// 调用接口将按钮插入到QTableWidget指定的行列中
m_pDeviceTable->setCellWidget(InsertRow, InsertColumn, pTestBtn);
// 绑定的响应函数
void CSystemTest::slotTestBtnClicked()
{
// 获取当前被点击的按钮
QPushButton* pSenderObj = qobject_cast<QPushButton*>(sender());
if (pSenderObj == nullptr)
{
return;
}
QModelIndex qIndex = m_pDeviceTable->indexAt(QPoint(pSenderObj->frameGeometry().x(), pSenderObj->frameGeometry().y()));
// 获取当前按钮所在的行和列
int row = qIndex.row();
int column = qIndex.column();
// 添加其他响应信息......
}
下图是自己实现的槽函数,点击后的效果,图片展示的是获取当前按钮所在的行和列并显示。
