项目中有时遇到动态创建QPushButton,同时要绑定QPushButton点击事件时,如果只有几个按钮,对应写几个槽函数就行了;如果有几百个按钮,每一个都写一个槽函数,这样就太麻烦了,本文结合一个例子介绍一种解决方案;
QTableView显示100行的表格,表格最后两列是编辑和删除按钮,为每一个删除和编辑按钮绑定一个槽函数:
设置表头
void CUsersForm::setTableHead()
{
if (ui->tabViewUsers->model() == nullptr)
{
QStandardItemModel* model = new QStandardItemModel(ui->tabViewUsers);
ui->tabViewUsers->setModel(model);
}
QStandardItemModel* model = ((QStandardItemModel*)ui->tabViewUsers->model());
QStringList head;
head << "序号" << "账号" << "员工姓名" << "手机号码" << "邮箱" << "部门" << "岗位" << "账号状态" << "操作" << "操作";
model->setHorizontalHeaderLabels(head);
ui->tabViewUsers->setStyleSheet("QHeaderView::section { background:green; color:white;min-height:3em;}");
ui->tabViewUsers->setGridStyle(Qt::SolidLine);
ui->tabViewUsers->horizontalHeader()->setStretchLastSection(true);
ui->tabViewUsers->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tabViewUsers->verticalHeader()->setVisible(false);
ui->tabViewUsers->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
显示表格数据
void CUsersForm::updateTableData(const QVector<QVector<QString> > &result)
{
QStandardItemModel* model = ((QStandardItemModel*)ui->tabViewUsers->model());
setTableHead();
if (result.size() == 0) return;
int start = model->rowCount();
int col = result[0].size();
int row = result.size();
for (int i = 0; i<row; ++i)
{
QList<QStandardItem*> list;
for (int j = 0; j<col; ++j)
{
list << new QStandardItem(result[i][j]);
}
model->insertRow(i + start, list);
QPushButton *pbtEdit = new QPushButton("编辑");
pbtEdit->setProperty("row", i);
QPushButton *pbtDel = new QPushButton("删除");
pbtDel->setProperty("row", i);
connect(pbtEdit, &QPushButton::clicked, this, &CUsersForm::handleEditBtnClicked);
connect(pbtDel, &QPushButton::clicked, this, &CUsersForm::handleDelBtnClicked);
ui->tabViewUsers->setIndexWidget(ui->tabViewUsers->model()->index(i, col-2), pbtEdit);
ui->tabViewUsers->setIndexWidget(ui->tabViewUsers->model()->index(i, col-1), pbtDel);
}
}
上面代码中pbtEdit->setProperty(“row”, i);和pbtDel->setProperty(“row”, i);是关键部分,给每个按钮设置唯一属性值,再到对应槽函数里面读取属性值,
void CUsersForm::handleEditBtnClicked()
{
QPushButton* btn = (QPushButton*)sender();
qDebug() << "[CUsersForm::handleEditBtnClicked]" << btn->property("row").toInt();
}
void CUsersForm::handleDelBtnClicked()
{
QPushButton* btn = (QPushButton*)sender();
qDebug() << "[CUsersForm::handleDelBtnClicked]" << btn->property("row").toInt();
}
在槽函数中读取设置的属性值,就知道编辑或者删除的是哪一行。