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

5
我有一个包含自定义小部件的 QVBoxLayout,这些小部件本身主要由标签和两个按钮组成。你可以将其几乎视为某种自制表格。我知道有现成的表格小部件可用,但我想使用自己的小部件。
我的目标是:当我点击其中一个小部件中的“向上”按钮时,它应该向上移动,或者换句话说:它应该以每次单击向上移动一步(或相应地向下)。这样做是否可能?我该如何实现?我需要这样一个用户友好的方式来设置布局中项目的顺序。
我开始尝试从我的小部件中获取父布局:
QVBoxLayout* myLayout = qobject_cast<QVBoxLayout*>(this->parentWidget());

看起来这样可以运行,但是接下来怎么做?谢谢你的帮助!


请查看 QBoxLayout::insertWidget - Kiwi
3个回答

8
你可以尝试像这样做:

您可以尝试如下操作:

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

看起来不错,谢谢!我本来希望有更优雅的方法(比如只是简单地设置一个新索引),但我想删除一个位置再添加到新位置可能是唯一可行的方式。 - Rob
更新:经过测试,只需要进行一个小修正:需要从“widget->parentWidget()->layout()”而不是“widget->parentWidget()”进行强制转换,以检索布局对象。 - Rob
@Robert 已修复,我只是从你的问题中复制了那一行。谢谢。 - C. E. Gesser

0

同意C.E. Gesser的观点,布局中没有像“setIndex”这样的接口来设置布局项。

如果您正在实现类似于棋盘上的象棋应用程序,其中移动小部件经常操作,则QGraphicsView + QGraphicsItem(sa QWidgetItem)可能会有所帮助。


-2

每次删除和重新创建小部件都会消耗内存。换句话说,删除小部件不会在运行时释放内存。 您应该使用setCurrentIndex()槽来设置所需的小部件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接