QT控件之(TableWidget)中添加控件点击所在控件获取当前行列号

该博客介绍了如何在Qt环境中使用QTableWidget添加QCheckBox控件,并通过信号槽机制实现点击检查框时获取当前选中行和列的方法。示例代码展示了在MainWindow类中设置表格布局,添加QCheckBox,并连接信号与槽函数,以便于在点击事件中获取单元格位置信息。

操作步骤就是:

首先是在tablewidget中加入控件,然后点击当前的单元格中的控件,获取当前所在的行号和列号

好了,话不多说,我来贴上源码:

MainWindow.h中:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QCheckBox>
#include <QDebug>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void BoxSlot(int);

private:
    Ui::MainWindow *ui;  
};
#endif // MAINWINDOW_H

2、MainWindow.cpp中

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->tableWidget->setRowCount(3);
    ui->tableWidget->setColumnCount(3);
    ui->tableWidget->setHorizontalHeaderLabels(QStringList({"Segment1","Segment2","Segment3"}));
    QCheckBox *checkBox = new QCheckBox();
    // 在QTableWidget中添加控件
    ui->tableWidget->setCellWidget(1,2,checkBox);
    connect(checkBox,SIGNAL(stateChanged(int)),this,SLOT(BoxSlot(int)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::BoxSlot(int value)
{
    //获取当前选中的行号
    QCheckBox *box = dynamic_cast<QCheckBox*>(this->sender());
    int x = box->frameGeometry().x();
    int y = box->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));
    int row = index.row();
    int column = index.column();
    qDebug()<<"11111=="<<row;
    qDebug()<<"2222=="<<column;

}

3、在main.cpp中

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

 最终实现如下:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值