简体   繁体   English

如何以编程方式更改布局中小部件的顺序?

[英]How to programmatically change the order of widgets in a layout?

I do have a QVBoxLayout that contains some custom widgets, which themselves mainly consist of a label and two buttons. 我确实有一个QVBoxLayout ,其中包含一些自定义小部件,它们本身主要由一个标签和两个按钮组成。 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. 我想要实现的是:当我单击其中一个小部件中的“向上”按钮时,它应该向上移动,或者QVBoxLayout :它应该以一种方式更改其在父QVBoxLayout中的当前位置/索引每次点击都会向上(或向下)移动一级。 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! 谢谢你的帮助!

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;
}

Agree with CE Gesser, there's no interface like "setIndex" for layoutitems within layout. 同意CE Gesser,在布局中没有用于布局项目的界面,例如“ setIndex”。

If you are implementing some application like a chess on chessboard, where moving widget operates frequently, QGraphicsView + QGraphicsItem (sa QWidgetItem) might be helpful. 如果您要实现象棋盘上的象棋这样的应用程序,其中移动小部件经常运行,则QGraphicsView + QGraphicsItem(即QWidgetItem)可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM