PDA

View Full Version : Keep a QStandardItem in QTreeView in edit mode till it is given a unique name



NameRakes
4th January 2017, 05:54
I have QStandardItem::text() displayed using QTreeView thus:
12271

I would like the names of the items under a parent to be unique. In this example, this is the flow of events:

First I double click on 'Table3', it goes into edit mode.

Then I change the name to 'Table2' - not a unique name, and then click on 'Table1'.

At which time the slot that is connected to theQStandardItemModel::itemChanged(QStandardItem*) signal is invoked. This slot checks for uniqueness among the siblings.

In this case it pops up a message box, asking the user to fix the error (not a modal dialog! Just a simple message box).

When the user hits 'OK' in the message box, the slot keeps the view of the original item 'Table3' in edit mode.


But it's too late! My slot exits, and the slot that triggered itemChanged(...) signal now goes on to processing the clicked() action of `Table1'.

You know my conundrum now: how do I put an infinite loop in my slot that checks for uniqueness of the item names? Without popping up a modal dialog!! I understand how I can do it by populating a text box in a dialog and check it when the user clicks OK. Is there a better way to enforce uniqueness of the item names as they are being created through GUI.

Thanks!

anda_skoa
4th January 2017, 15:09
One option you have is a custom item delegate.

Basically the editing of an item happens through an "editor widget" created by the item delegate.
For a string that widget is a QLineEdit.

With a custom delegate you can either provide a widget that does not allow input that you do not want, or you can still provide a QLineEdit but not accept the value in the delegate's setModelData() method.

Cheers,
_

NameRakes
5th January 2017, 06:41
Thanks to your pointer, after some more reading, I have implemented your suggestion with a minor variation. The variation came from the fact that I did not want the user to leave the editor without providing a unique name. There can be complications catching this in setModelData() - what to do if the data is invalid? So this is what I have done:

Still I have the derived (custom) QStyledItemDelegate. This now attaches a custom QValidator to the editor widget. Whenever the editor is created, the custom delegate emits a signal asking for a list of names to check against, which is provided by my custom widget implementing MV. The custom validator performs the check in the validate() method. Now the editor won't budge an inch, there is no way for the user to enter a non-unique name.

It works great! Thanks to you and others in the forum, I have a much better understanding of the MVD (I am calling it MVD instead of MV) architecture.