Qt中如何在QTableWidget中一个单元格插入多个按钮,如何正确获取插入的按钮的行列数

一、在QTableWidget单元格中插入单个按钮,调用setCellWidget直接插入:

   QPushButton *btn = new QPushButton();    
   btn->setText(tr("查看"));    
   ui->tableWidget->setCellWidget(0,4,btn);

在这里插入图片描述
二、在QTableWidget单元格中插入两个按钮(多个类似),新增QWidget在其中添加布局,布局中添加按钮:

   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);

在这里插入图片描述
三、按钮点击时获取按钮所在的行列数:
1)只有单个按钮时:
方法1:使用mapToParent来获取位置

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();

工程源码下载地址:https://download.csdn.net/download/juzone/11959062

  • 24
    点赞
  • 139
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值