Qt表格(QTableWidget)中复选框(QCheckBox)的使用

本文阅读 1 分钟
首页 应用开发 正文

1 引言

最近项目里要在QTableView中使用复选框,但是原生的复选框默认为左对齐,很不美观,于是查资料得出QTableView中使用复选框的方法.

2 添加

// 创建组件
QWidget* widget = new QWidget;
// 创建水平布局
QHBoxLayout* layout = new QHBoxLayout;
// 创建复选框
QCheckBox* box = new QCheckBox;
// 添加复选框到布局
layout->addWidget(box);
// 设置外边距
layout->setContentsMargins(0, 0, 0, 0);
// 设置对齐方式
layout->setAlignment(box, Qt::AlignCenter);
// 为组件设置布局
widget->setLayout(layout);
// 向表格中添加组件
ui.tableWidget->setCellWidget(row, column, widget);

3 获取状态

// 遍历行
for (int row = 0; row < ui.tableWidget->rowCount(); row++)
{
    // 遍历列
    for (int column = 0; column < ui.tableWidget->columnCount(); column++)
    {
        QCheckBox* checkBox = reinterpret_cast<QCheckBox*>(ui.tableWidget->cellWidget(row, column)->layout()->itemAt(0)->widget());
        qDebug() << "选中状态[" << row << "," << column << "]: " << checkBox->isChecked();
    }
}
本文来自投稿,不代表本站立场,如若转载,请注明出处:
QLineEdit限制数值输入范围
« 上一篇 03-04
QList中Item修改的问题
下一篇 » 03-14