How to programmatically change the order of widget

2019-04-13 06:32发布

I do have a QVBoxLayout that contains some custom widgets, which themselves mainly consist of a label and two buttons. You can almost speak of some kind of selfmade table in a way. I know that there are ready-made table widgets available, but I'd like to use my own.

What I want to achieve is this: when I click the "up" button in one of the widgets, it should move up, or to put it differently: it should change its current position/index within the parent QVBoxLayout in a way that it moves one step up (or down accordingly) with every click. Is that possible? How can I achieve that? I need that as a user-friendly way to set the order of items within that layout.

I began with trying to get the parent layout from within my widget:

QVBoxLayout* myLayout = qobject_cast<QVBoxLayout*>(this->parentWidget());

That seems to work, but how to go on from here? Thanks for your help!

2条回答
Animai°情兽
2楼-- · 2019-04-13 07:14

You can try something like this:

enum MoveDirection { MoveUp, MoveDown };
bool move(QWidget *widget, MoveDirection direction) {
  QVBoxLayout* myLayout = qobject_cast<QVBoxLayout*>(widget->parentWidget()->layout());

  //Gets the index of the widget within the layout
  const int index = myLayout->indexOf(widget); 

  if (direction == MoveUp && index == 0) {
    //Can't move up
    return false;
  }

  if (direction == MoveDown && index == myLayout->count()-1 ) {
    //Can't move down
    return false;
  }

  //Compute new index according to direction
  const int newIndex = direction == MoveUp ? index - 1 : index + 1;
  //Remove widget from layout
  myLayout->removeWidget(widget);
  //Insert widget at new position
  myLayout->insertWidget(newIndex , widget);

  return true;
}
查看更多
SAY GOODBYE
3楼-- · 2019-04-13 07:26

Agree with C.E. Gesser, there's no interface like "setIndex" for layoutitems within layout.

If you are implementing some application like a chess on chessboard, where moving widget operates frequently, QGraphicsView + QGraphicsItem (sa QWidgetItem) might be helpful.

查看更多
登录 后发表回答