需要在cell中增加按钮。
主要代码(没写类名):
void InsertTableInfo(const QStringList &listInfo, bool bChecked) { int nRowCount = ui->tableWidget->rowCount(); ui->tableWidget->setRowCount(nRowCount + 1); ui->tableWidget->setRowHeight(nRowCount, 60); for(int i = 0; i < listInfo.size(); i++) { if(i == 9){//按钮所在列 SetItem(ui->tableWidget, nRowCount, i + 1); continue; } QTableWidgetItem* item = new QTableWidgetItem(listInfo.at(i)); item->setTextAlignment(Qt::AlignCenter); ui->tableWidget->setItem(nRowCount, i + 1, item); } } void SetItem(QTableWidget *table, int row, int column) { QWidget* pWidget = new QWidget(table); QHBoxLayout *hLayout = new QHBoxLayout(pWidget); //创建布局 QPushButton *pBtnDraw = new QPushButton(ui->tableWidget); QPushButton *pBtnModify = new QPushButton(ui->tableWidget); QPushButton *pBtnDelete = new QPushButton(ui->tableWidget); SetBtnStyle(pBtnDraw, "31,110,212", "绘制"); SetBtnStyle(pBtnModify, "30,227,207", "修改"); SetBtnStyle(pBtnDelete, "204,153,0", "删除"); hLayout->addWidget(pBtnDraw); hLayout->addWidget(pBtnModify); hLayout->addWidget(pBtnDelete); hLayout->setContentsMargins(0, 0, 0, 0);// connect(pBtnDraw,SIGNAL(clicked()),this,SLOT(SlotBtnClicked())); // 添加 按钮 点击处理 connect(pBtnModify,SIGNAL(clicked()),this,SLOT(SlotBtnClicked())); connect(pBtnDelete,SIGNAL(clicked()),this,SLOT(SlotBtnClicked())); table->setCellWidget(row,column,pWidget); } void SetBtnStyle(QPushButton *pBtn, QString clr, QString btnTxt)//注意qstring clr的格式写法 { pBtn->setText(btnTxt); QString style = QString("QPushButton{min-height:40px;font-size:22px;color:rgb(255, 255, 255);background:rgba(%1,0.8);border:1px;border-radius:20px;padding:2px 2px;font-family:Microsoft YaHei;}" "QPushButton:hover{color:rgb(255, 255, 255);border-style:solid;background: rgba(%2,0.6);border-radius:20px;border:1px;font-family:Microsoft YaHei;}" "QPushButton:pressed{color:rgb(255, 255, 255);border-style:solid;border-radius:20px;background: rgba(%3,0.4);border:1px;font-family:Microsoft YaHei;}").arg(clr).arg(clr).arg(clr); pBtn->setStyleSheet(style); } void SlotBtnClicked()//槽函数 { QPushButton *senderObj = qobject_cast<QPushButton*>(sender()); if (senderObj == nullptr) { return; } QModelIndex idx = ui->tableWidget->indexAt(QPoint(senderObj->parentWidget()->frameGeometry().x(), senderObj->parentWidget()->frameGeometry().y())); int row = idx.row(); QString btnTxt = senderObj->text(); if(btnTxt.compare("绘制") == 0){ qDebug() << QString("按下第 %1 行 绘制 按钮").arg(row); } else if (btnTxt.compare("修改") == 0) { qDebug() << QString("按下第 %1 行 修改 按钮").arg(row); } else if (btnTxt.compare("删除") == 0) { qDebug() << QString("按下第 %1 行 删除 按钮").arg(row); } else { qDebug() << "错误"; } }
标签:qtablewidget,tableWidget,添加,ui,QPushButton,按钮,new,border,255 From: https://www.cnblogs.com/warmlight/p/16940440.html