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

一、在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://blog.csdn.net/juzone/article/details/102915616

你可能感兴趣的:(QT,qt,ui,开发语言)