一、在QTableWidget单元格中插入单个按钮,调用setCellWidget直接插入:
QPushButton *btn = new QPushButton();
btn->setText(tr("查看"));
ui->tableWidget->setCellWidget(0,4,btn);
QPushButton *btn_1 = new QPushButton();
btn_1->setText(tr("查看"));
QPushButton *btn_2 = new QPushButton();
btn_2->setText(tr("修改"));
QWidget *tmp_widget = new QWidget();
QHBoxLayout *tmp_layout = new QHBoxLayout(tmp_widget);
tmp_layout->addWidget(btn_1);
tmp_layout->addWidget(btn_2);
tmp_layout->setMargin(0);
ui->tableWidget->setCellWidget(1,4,tmp_widget);
QPushButton *btn = (QPushButton *)sender();
int x = btn->mapToParent(QPoint(0,0)).x();
int y = btn->mapToParent(QPoint(0,0)).y();
QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));
int row = index.row();
int col = index.column();
方法2:使用frameGeometry来获取位置
QPushButton *btn = (QPushButton *)sender();
int x = btn->frameGeometry().x();
int y = btn->frameGeometry().y();
QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));
int row = index.row();
int col = index.column();
2)有两个按钮时:
方法1:使用mapToParent来获取位置
QPushButton *btn = (QPushButton*)sender();
QWidget *w_parent = (QWidget*)btn->parent();
int x = w_parent->mapToParent(QPoint(0,0)).x();
int y = w_parent->mapToParent(QPoint(0,0)).y();
QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));
int row = index.row();
int col = index.column();
方法2:使用frameGeometry来获取位置
QPushButton *btn = (QPushButton*)sender();
QWidget *w_parent = (QWidget*)btn->parent();
int x = w_parent->frameGeometry().x();
int y = w_parent->frameGeometry().y();
QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));
int row = index.row();
int col = index.column();
联系客服