QTableWidget中添加button
QTableWidget 中插入QCheckBox复选框,状态判断,居中显示
QTableWidget使用setCellWidget设置控件居中显示
界面
添加button
for (int i = 0; i < 3; i++)
{
QPushButton *pBtn = new QPushButton(QIcon(":/image/point.png") ,"");
pBtn -> setIconSize(QSize(20, 20));
ui.tableWidget->setCellWidget(i, 5, pBtn);
connect(pBtn, SIGNAL(pressed()), this, SLOT(OnBtnRollbackClicked()));
}
槽函数:获取行号
void OnBtnRollbackClicked()
{
QPushButton *senderObj = qobject_cast<QPushButton*>(sender());
if (senderObj == nullptr)
{
return;
}
QModelIndex idx = ui.tableWidget->indexAt(QPoint(senderObj->frameGeometry().x(), senderObj->frameGeometry().y()));
int row = idx.row();
//do something
}
添加QCheckBox
QCheckBox * pCheckBox = new QCheckBox();
ui.tableWidget->setCellWidget(1, 4, pCheckBox);
connect(pCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SlotSetChecked(int)));
如果控件需要居中
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout();
QCheckBox *checkBox = new QCheckBox;
layout->addWidget(checkBox, 0, Qt::AlignCenter);
layout->setMargin(0);
widget->setLayout(layout);
connect(checkBox, &QCheckBox::stateChanged, this, &CConsult::SlotSetChecked);
ui->table->setCellWidget(1,4, widget);
任何在QTableWidget中需要居中显示的控件,都建议:
- new QWidget
- new 一个布局,QHBoxLayout 就可以
- QWidget 加入布局加入 控件居中
- 最后把 QWidget 加到QTableWidget中
槽函数
void SlotSetChecked(int)
{
QCheckBox *senderObj = qobject_cast<QCheckBox*>(sender());
if (senderObj == nullptr)
{
return;
}
QModelIndex idx = ui.tableWidget->indexAt(QPoint(senderObj->frameGeometry().x(), senderObj->frameGeometry().y()));
int row = idx.row();
bool enable = senderObj->isChecked();
//dosomething
}