QTreeview: how to reposition defalut text element

Could you tell me how to reposition an item in a QTreeView. By default, an element is displayed on the left side on the left and in the center of the element field. But how can I change it so that it appears at the top

+4
source share
1 answer

Using the Qt Inline Model

If you use, for example, QFileSystemModel you need to inherit it and override the behavior of data() :

 class MyFileSystemModel : public QFileSystemModel { public: QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const { if (role == Qt::TextAlignmentRole) return Qt::AlignTop; //maybe different result depending on column/row else return QFileSystemModel::data(index, role); } 

and then use this class.

Using a custom item model

If you have implemented your own model model, all you have to do is handle Qt::TextAlignmentRole in data() :

 QVariant MyTreeModel::data (const QModelIndex &index, int role) const { if (role == Qt::TextAlignmentRole) return Qt::AlignTop; //maybe different result depending on column/row //handle other roles return QVariant(); } 

Now the tree view automatically aligns the elements up.

If you want to further customize the look, here are the roles that QTreeView uses. For more customization, I think you should implement your own QTreeView subclass.

Using QStandardItemModel

If you did not implement your own model, but used QStandardItemModel , you need to call setTextAlignment(Qt::Alignment alignment) with Qt::AlignTop on standard elements before adding them to the model.

+4
source

Source: https://habr.com/ru/post/1433570/


All Articles