如何在QTableWidget中实现QCheckBox

2025-04-29 11:56:48
推荐回答(2个)
回答1:

#include "widget.h"
#include "ui_widget.h"
#include
#include
#include
#include
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
/*这是ui文件中没有放qtablewidget控件时在里面插入QCkeckBox的方法*/
// QTableWidget *table=new QTableWidget(5,5);
// QCheckBox *abc=new QCheckBox("");
// table->setCellWidget(0,0,abc);
// QHBoxLayout *mainLayout = new QHBoxLayout;
// mainLayout->addWidget(table);
// setLayout(mainLayout);

/*这是ui文件中已经放了QtableWieget控件时在里面插入QCheckBox的方法*/
// QCheckBox *abc=new QCheckBox("");
// ui->tableWidget->setColumnCount(2);
// ui->tableWidget->setRowCount(2);
// ui->tableWidget ->setCellWidget(0,0,abc);

/*
这是利用QTableWidget自带的属性插入QCheckBox的方法,据说前两中方法不能读取单选框的选择状态(我测试了一下,发现这种说法并不完
全对,尽管失败了)而这种可以读取状态的方法是利用QTableWidget::cellChanged()函数,检查单元格内容的变化,然后连接此信
号,在槽函数中检测checkBox的状态。

connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(changeTest(int, int)));

void changeTest(int row, int col)

{

if(tableWidget ->item(row, col)->checkState() == Qt::Checked) //选中

...

else

...

}
*/

[cpp] view plain copy

QTableWidgetItem *asd=new QTableWidgetItem();
asd->setCheckState(Qt::Checked);
ui->tableWidget->setColumnCount(3);
ui->tableWidget->setRowCount(3);
ui->tableWidget->setItem(0,0,asd);

}

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

回答2:

include "widget.h" #include "ui_widget.h" #include #include #include #includeWidget::Widget(QWidget *parent) : QWidget(parent), ui(new