如何以编程方式更改布局中小组件的顺序
How to programmatically change the order of widgets in a layout?
我确实有一个包含一些自定义小部件的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()
插槽
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 函数调用中参数的顺序重要吗
- 为什么不;名字在地图上是按顺序排列的吗
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何将 txt 文件中的行分隔为组件C++
- 数到第n个楼梯的路(顺序无关紧要)
- 优先顺序:智能指针和类析构函数
- 在循环中按顺序遍历成员变量
- 独立读取-修改-写入顺序
- QML按钮点击功能执行顺序
- C++中数据类型修饰符的顺序
- 当比特(而不是字节)的顺序至关重要时的持久性
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 通过选项卡的文本设置QTabWidget顺序
- c++11评估顺序(未定义的行为)
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 如何在C++中递归地按相反顺序打印集合
- 如何以编程方式更改布局中小组件的顺序
- 允许智能指针按特定顺序删除 SDL 组件
- 当顺序很关键时,初始化c++组件的最佳实践