操作步骤就是:
首先是在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();
}

最终实现如下:

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

被折叠的 条评论
为什么被折叠?



