设置QStandardItem的CheckBox选项框关闭与开启

1.使用背景:
QStandardItem与TreeView结合时,其自带的checkBox功能很好用,可以通过获取其子节点或者根据获取索引遍历根节点下所有的节点,进而控制checkBox的动态显示或隐藏,勾选或取消。

// 根据按钮“全选”->“取消全选”来设定全部选中或者取消
void MsgDataCenterDlg::on_pushButton_AllSelect_clicked() 
{
     
    int i_RowCount = 0;
    QModelIndex TempIndex;
    i_RowCount = m_pBaliseMsgModel->rowCount();
    for(int i = i_RowCount - 1; i >= 0;i--)
    {
     
        TempIndex = m_pBaliseMsgModel->index(i, 2);
        if (ui->pushButton_AllSelect->text() == "全选")
        {
     
            if(Qt::Checked != TempIndex.data(Qt::CheckStateRole))
            {
     
                m_pBaliseMsgModel->setData(TempIndex, Qt::Checked, Qt::CheckStateRole);
            }
        }
        else
        {
     
            if(Qt::Unchecked != TempIndex.data(Qt::CheckStateRole))
            {
     
                m_pBaliseMsgModel->setData(TempIndex, Qt::Unchecked, Qt::CheckStateRole);
            }
        }
    }
}

// item->setData(QVariant(), Qt::CheckStateRole) 传入空值即可控制CheckBox显示与隐藏

// 传入显示状态status来控制QStandardItem的checkBox的显示与隐藏
void PartOrAllVerifyDlg::setCheckStatusVisible(bool status)
{
     
    QStandardItemModel * model = (QStandardItemModel *)ui->treeView->model();
    int rowCounts = model->rowCount();
    for (int i = 0; i < rowCounts; i++)
    {
     
        if (model->item(i)->hasChildren())
        {
     
            int rowC  = model->item(i)->rowCount();
            for (int j = 0; j < rowC; j++)
            {
     
                model->item(i)->child(j)->setCheckable(status);
                model->item(i)->child(j)->setSelectable(status);
                if (!status)
                {
     
                    model->item(i)->child(j)->setData(QVariant(), Qt::CheckStateRole);
                }
            }
        }
    }
    ui->treeView->setModel(model);
    ui->treeView->update();
}

你可能感兴趣的:(C++,Qt,窗体)