c++ - QTreeView:多级列的层次上下文

标签 c++ qt qtreeview qabstractitemmodel

我正在寻找一种更好的方法来在树中显示多级分层数据,其中每列的含义根据树中的级别而变化

我正在使用 QTreeViewQAbstractItemModel 来显示我的模型数据。

每个模型行都有不同数量的列不同的列名称,具体取决于它在层次结构中的级别。

为了为树中显示的数据提供上下文,我需要为层次结构中的每个级别提供列标题。

问题是 QTreeView 只有一组列标题。

当前方法

目前,每次选定的行发生变化时,我都会更改标题。

我通过连接到 TreeView 的 selectionModel 并在每次选择更改时使用新的 QModelIndex 发出信号来实现这一点

void Window::slotOnSelectionChanged(const QItemSelection& new_selection, const QItemSelection& old_selection)
{
    QItemSelectionModel* selection_model = _view->selectionModel();
    QModelIndex index = selection_model->currentIndex();
    if (index.isValid())
        emit selectedIndexChanged(index);
}

在我的模型中,我连接到这个信号,当它触发时,存储选定的行,并强制更新列标题

void Model::slotOnSelectedIndexChanged(QModelIndex index)
{
    assert(index.isValid());
    _selected_row = modelRow(index);
    emit headerDataChanged(Qt::Horizontal, 0, _root->numColumns());
}

QAbstrateItemModel::headerData 回调中,我然后使用 selected_row 获取当前选定行的标题

QVariant Model::headerData(int i, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole)
    {
        switch (orientation)
        {
            case Qt::Horizontal:
                return QVariant(_selected_row->header(i));
            ...

结果

结果如下所示 - 注意列标题​​如何随着所选行的变化而变化。

enter image description here enter image description here enter image description here

问题

仅查看 View 并不能立即看出每个数据是什么,因此用户需要更改行才能查看每列的实际含义。

我想要的是有某种嵌入式列标题行,层次结构中每个级别 1 个。

像这样:

enter image description here

问题

  • 这可能吗?
  • 如果有更好的方法为树中的数据提供上下文,请提供建议。

最佳答案

@Kuba Ober的建议下我在树的每个层次结构中的位置 0 添加了一个额外的行。它没有 child 。

然后将模型配置为 index.row() == 0 的特殊情况,知道该行是标题行而不是数据行。

例如:在 Model::flags 中,标题行不可编辑

Qt::ItemFlags Model::flags(const QModelIndex& index) const
{
    Qt::ItemFlags item_flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;

    // header row is not editable
    if (index.row() != 0)
        item_flags |= Qt::ItemIsEditable;

    return item_flags;
}

我现在为 headerData 返回空字符串,因为标题在树本身中

QVariant Model::headerData(int i, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole)
    {
        switch (orientation)
        {
            case Qt::Horizontal:
                return QVariant(); // no column header, it's already in the tree
            ...

我还更改了页眉的背景颜色,使其突出显示

QVariant Model::data(const QModelIndex& index, int role)  const
{
    switch (role)
    {
        case Qt::BackgroundColorRole:
            if (index.row() == 0) // header row
                return QColor(Qt::darkGray);
            break;
        ...

结果几乎就是我要找的结果

enter image description here

关于c++ - QTreeView:多级列的层次上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32749504/

相关文章:

c++ - 逗号运算符未能更新基类构造的输入参数

C++抽象基类和继承

c++ - Qt QTreeView : Only allow to drop on an existing item

python - PyQt 中支持拖放的 QTreeView

c++ - 以自定义类作为键的 std::map 始终返回 1 的大小

c++ - 无输出转换

Qt:使用 QSharedMemory 的单实例应用程序

qt - QFile readAll() 返回的 QBytearray 是什么

c++ - 将文本和占位符、变量复制到剪贴板

c++ - Qt - QPushButtons 代替 QTreeView 项目