Reputation: 2949
I have a QTreeWidget that can have many rows but only 3 columns:
In the picture I have selected my last column. What I would like to do, is to disable the last column for every item in the tree UNLESS it is selected. So in my situation only the pidtest.xml
item would have enabled checkbox. How can I do this with existing methods?
Upvotes: 4
Views: 2670
Reputation: 14360
Here you have a complete working example on how to do that.
As Pavel Strakhov have pointed out, the example use a QTreeView, since QTreeWidgetItem do not support "partial disabling".
In the example a TreeView is displayed, showing 2 columns (name, enabled). You will be able to edit the first column only if the second is true.
There is no implementation in the example for changing the values, you will have to add the
setData
function to the model to do that.
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();
}
Upvotes: 2