一、添加复选框QCheckBox初始化默认状态,效果图
主要代码:
void MainWindow::setTableInfo()
{
QTableWidgetItem *xh_item;
QTableWidgetItem *info_item;
for(int i = 0;i < 2;i++)
{
xh_item = new QTableWidgetItem(QString::number(i));
info_item = new QTableWidgetItem("*************");
ui->m_table->setItem(i,0,xh_item);
ui->m_table->setItem(i,1,info_item);
}
//添加复选框
QCheckBox * pCheckBox ;
QWidget * pBoxWidget;
QHBoxLayout * hBox ;
for(int j = 0;j < 2;j++)
{
pCheckBox = new QCheckBox();
pBoxWidget = new QWidget(this);
hBox = new QHBoxLayout();
//调整框的大小,添加选中图片
pCheckBox->setStyleSheet("QCheckBox::indicator{width:30px;height:30px}"
"QCheckBox::indicator:checked {image: url(:/new/prefix1/true.png);}");
hBox->addWidget(pCheckBox);
//设置默认选中状态
pCheckBox->setChecked(true);
hBox->setMargin(0);
hBox->setAlignment(pCheckBox,Qt::AlignCenter);
pBoxWidget->setLayout(hBox);
ui->m_table->setCellWidget(j,2,pBoxWidget);
}
}
二、添加两个复选框QCheckBox的互斥功能,同时只能有一个选中 效果图
主要代码:
QCheckBox * pCheckBox ;
QWidget * pBoxWidget;
QHBoxLayout * hBox ;
for(int j = 0;j < 2;j++)
{
pCheckBox = new QCheckBox();
pBoxWidget = new QWidget(this);
hBox = new QHBoxLayout();
//调整框的大小,添加选中图片
pCheckBox->setStyleSheet("QCheckBox::indicator{width:30px;height:30px}"
"QCheckBox::indicator:checked {image: url(:/new/prefix1/true.png);}");
hBox->addWidget(pCheckBox);
//设置默认选中状态
// pCheckBox->setChecked(true);
hBox->setMargin(0);
hBox->setAlignment(pCheckBox,Qt::AlignCenter);
pBoxWidget->setLayout(hBox);
ui->m_table->setCellWidget(j,2,pBoxWidget);
m_checkBoxList.append(pCheckBox);
}
mutexCheckBox(m_checkBoxList, false);
互斥代码:文章来源:https://www.toymoban.com/news/detail-547928.html
for(auto check:checkBoxList)
{
if(check)
{
QCheckBox::connect(check,&QCheckBox::clicked,[=]
{
Qt::CheckState checkState = check->checkState();
for(auto it:checkBoxList)
{
if(it && it != check)
{
if(checkState == Qt::Unchecked)
{
if(unchecked)
{
it->setCheckState(Qt::Checked);
}
}
else
{
it->setCheckState(Qt::Unchecked);
}
}
}
});
}
}
数据选中判断文章来源地址https://www.toymoban.com/news/detail-547928.html
QString text;
for(int i= 0;i<m_checkBoxList.size();i++)
{
if(m_checkBoxList[i]->isChecked())
{
QString str = ui->m_table->item(i,0)->text();
text = QString::fromLocal8Bit("选中第");
text.append(str).append(QString::fromLocal8Bit("行数据"));
ui->m_text->setText(text);
return;
}
}
text = QString::fromLocal8Bit("没有数据选中");
ui->m_text->setText(text);
到了这里,关于QTableWidget 实现添加 QCheckBox的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!