1.相关描述
继承QCheckBox的类MyCheckBox,利用QTableWidget的setCellWidget方式添加MyCheckBox类的对象
2.相关页面
3.相关代码
mycheckbox.h
#ifndef MYCHECKBOX_H #define MYCHECKBOX_H#include <QCheckBox> #include <QObject>class MyCheckBox : public QCheckBox { public:MyCheckBox(QWidget *parent = nullptr);void SetID(int id);int GetID(); private:int mId; };#endif // MYCHECKBOX_H
mycheckbox.cpp
#include "mycheckbox.h" #include <QDebug> MyCheckBox::MyCheckBox(QWidget *parent):QCheckBox(parent) {}void MyCheckBox::SetID(int id) {this->mId = id; }int MyCheckBox::GetID() {return mId; }
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H#include <QMainWindow>QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACEclass MainWindow : public QMainWindow {Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow(); public slots:void recvCheckBox(bool checked); private:Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
mainwindow.cpp
#include "checkboxdelegate.h" #include "mainwindow.h" #include "mycheckbox.h" #include "ui_mainwindow.h"#include <QCheckBox> #include <QDebug> MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow) {ui->setupUi(this);ui->tableWidget->setColumnCount(3);ui->tableWidget->setRowCount(3);for(int i = 0; i < 3; i++){MyCheckBox *checkBox = new MyCheckBox();checkBox->setText(QString::number(i+1));QWidget *widget = new QWidget();QHBoxLayout *layout = new QHBoxLayout(widget);layout->addWidget(checkBox);layout->setAlignment(Qt::AlignCenter);layout->setContentsMargins(0, 0, 0, 0);widget->setLayout(layout);ui->tableWidget->setCellWidget(i, 0, widget);checkBox->SetID(i);connect(checkBox, &MyCheckBox::clicked, this, &MainWindow::recvCheckBox);}// ui->tableWidget->insertRow(3);// MyCheckBox *checkBox = new MyCheckBox();// checkBox->setText(QString::number(3));// QWidget *widget = new QWidget();// QHBoxLayout *layout = new QHBoxLayout(widget);// layout->addWidget(checkBox);// layout->setAlignment(Qt::AlignCenter);// layout->setContentsMargins(0, 0, 0, 0);// widget->setLayout(layout);// ui->tableWidget->setCellWidget(3, 0, widget);// checkBox->SetID(3);// connect(checkBox, &MyCheckBox::clicked, this, &MainWindow::recvCheckBox);}MainWindow::~MainWindow() {delete ui; }void MainWindow::recvCheckBox(bool checked) {MyCheckBox* checkBox = static_cast<MyCheckBox*>(sender());qDebug() << "checked = " << checked << ";id = " << checkBox->GetID(); }