Disable only one item in a QTreeWidget

I have a QTreeWidget that can have many rows, but only 3 columns:

enter image description here

In the picture, I have selected my last column. What I would like to do is disable the last column for every item in the tree, if not selected. So in my situation, only the pidtest.xml element would include the checkbox. I don't know how to do this with existing methods. I will help everyone!

+3


source to share


1 answer


You have a complete working example here on how to do this.

As Pavel Strakhov pointed out, use QTreeView in the example , since QTreeWidgetItems do not support "partial disconnection".

The example shows a TreeView showing 2 columns (name, included). You will only be able to edit the first column if the second is correct.



There is no implementation in the example for changing values, you will need to add a function setData

to the model for this.

Complete example:

#include <QtWidgets/QApplication>
#include <QTreeView>
#include <QAbstractTableModel>
#include <QString>
#include <QVariant>
#include <QList>

typedef struct entry_{
    entry_(const QString &n, bool e) : name(n), enabled(e) {}
    QString name; bool enabled;
} table_entry_t;

class SimpleModel : public QAbstractTableModel
{
public:
    SimpleModel(QWidget *parent = nullptr) : QAbstractTableModel(parent)
    {
        m_entries = {
            {"Jhon Doe", false},
            {"Jhon Doe Jr.", true}
        };
    }

    QVariant data(const QModelIndex &index, int role) const {
        switch (role) {
        case Qt::DisplayRole:
            table_entry_t entry = m_entries[index.row()];
            if (index.column() == 0)
                return QVariant(entry.name);
            if (index.column() == 1)
                return QVariant(entry.enabled);
        }
        return QVariant();
    }

    Qt::ItemFlags flags(const QModelIndex &index) const {
        Qt::ItemFlags flags = QAbstractTableModel::flags(index);
        if (!m_entries[index.row()].enabled && index.column() == 0)
            flags ^ Qt::ItemIsEnabled;
        else
            flags |= Qt::ItemIsEditable;
        return flags;
    }

    int rowCount(const QModelIndex &parent /* = QModelIndex() */) const {Q_UNUSED(parent); return static_cast<int>(m_entries.size());}
    int columnCount(const QModelIndex &parent /* = QModelIndex() */) const {Q_UNUSED(parent); return 2; }

private:
    QList<table_entry_t> m_entries;
};


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTreeView tree;
    SimpleModel *model = new SimpleModel();
    tree.setModel(model);
    tree.show();
    return a.exec();
}

      

+2


source







All Articles