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

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

本文关键字:组件 顺序 布局 编程 方式更      更新时间:2023-10-16

我确实有一个包含一些自定义小部件的QVBoxLayout,这些小部件本身主要由一个标签和两个按钮组成。你几乎可以以某种方式谈论某种自制的桌子。我知道有现成的表格小部件可用,但我想使用我自己的。

我想要实现的是:当我单击其中一个小部件中的"向上"按钮时,它应该向上移动,或者换句话说:它应该更改其在父QVBoxLayout中的当前位置/索引,每次单击时都会向上移动(或相应地向下移动)。这可能吗?我怎样才能做到这一点?我需要它作为一种用户友好的方法来设置该布局中项目的顺序。

我首先尝试从我的小部件中获取父布局:

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

这似乎有效,但如何从这里继续?感谢您的帮助!

你可以尝试这样的事情:

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

同意 C.E. Gesser,布局中的布局项没有像"setIndex"这样的接口。

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

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