问题
I already have a tree model view that contains columns with a label, text edit, and a check button. What I am trying to add is a push button. Here is where I'm stuck:
- In the "flags" function which namespace will I use?
- In the "data" function what would be the role of the push button? (for example in the check button case I used the
Qt::CheckStateRole
) - In the "data" function (which returns a
QVariant
) what should I return? The button created?
I have looked at other answers regarding this topic and the most popular answer suggested using a setIndexWidget
however I am not sure how. Last note, I am attempting to do this programmatically not using the UI designer.
Thank you!
回答1:
Before anything else, you seem a bit confused about how Qt's model/view Framework is working. I suggest you go check Qt documentation about it: http://doc.qt.io/qt-5/model-view-programming.html
The answers to your 3 questions:
You do not need to use any namespaces in
Qt::ItemFlags QAbstractItemModel::flags(const QModelIndex &index) const
. Just return the particularQt::ItemFlags
(i.e combination ofQt::ItemFlag
) which suits your index. This has nothing to do with the fact that you want aQPushButton
in your view. I think your are confused by theQt::ItemIsUserCheckable
flag, which make the view display a check box. However that is not what this flag really does, actually it just tells the view to offer a mean for the user to change theQt::CheckStateRole
of the index. The default behaviour of the view is to do it by display aQCheckBox
.There are no roles associated with push buttons. You can use
Qt::CheckStateRole
orQt::EditRole
, it depends on the method you choose to display theQPushButton
.In
QVariant QAbstractItemModel::data(const QModelIndex &index, int role = Qt::DisplayRole) const
, whenrole
isQt::CheckStateRole
orQt::EditRole
, you may return a boolean which will control the state of theQPushButton
. However, you should NEVER return aQWidget
(or derived), the model handles data, not how they are displayed.
A solution:
Reimplement QAbstractItemDelegate
(or QStyledItemDelegate
). Rewrite:
createEditor()
: create aQPushButton
.setEditorData()
: set theQPushButton
state using the index and the role you used inQAstractItemModel::data()
.setModelData()
: update the model according to theQPushButton
state.
Set your delegate on your view (QTreeView::setItemDelegateForColumn()
). At this point you will get a push button only when in edition. You can then call QAbstractItemView::openPersistentEditor()
to make it always visible.
来源:https://stackoverflow.com/questions/38796335/qpushbuttons-in-a-column-of-a-treeview