Search code examples
c++qt

QTreeView Move Item with Button


I'm using a QTreeView with a QStandardItemModel and I'm trying to figure out how to move items up and down the tree using buttons . I can do drag and drop no problem, but what I would like to do is have some buttons associated with "move up" and "move down" functions. I just cant find anything on the subject. There seems to be a "moveRow()" function for the model object, but I cant find any documentation on it so I'm not sure if its what I need. Any information you could give to point me in the right direction would be greatly appreciated!

PS Here are my QT Creator stats: Qt Creator 2.6.2 Based on Qt 5.0.1 (64 bit)


Solution

  • Your hunch is correct. moveRow() is the right function to call.

    To move items within one parent (it's a tree, after all), you'd do moveRow(parent, index.row(), parent, index.row() + delta), where delta is set to 1 or -1 depending on whether you move down or up, respectively.

    If you want to allow items to be moved between parents, you'll need additional logic to figure out the destination parent if the item would be moved past its parent.

    Do note that it's considered bad design if the move button are separate from the items to be moved. Your delegate should display up and down arrows for each item, in its row, so that you can move things with one click. When there is a contiguous selection, the delegates should merge the up/down arrows to cover all of the items. When the selection is non-contiguous, the up/down arrows should disappear.

    With separate buttons, you need two clicks: first select the item, then click up/down. This sucks from user experience point of view.