打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

2022.07.30 北京

关注

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

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


二、在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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11


三、按钮点击时获取按钮所在的行列数:
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();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

方法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();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

方法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();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
setStyleSheet来设置图形界面的外观
pyqt5 -——基本功能(HelloWorld)
Qt----学习之路
PyQT5线程:多线程(QThread),线程锁(QMutex)
pyqt5 如何让多个QAction实现单选
QMetaObject::connectSlotsByName: No matching signal for……
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服