[英]How to programmatically change the order of widgets in a layout?
我确实有一个QVBoxLayout
,其中包含一些自定义小部件,它们本身主要由一个标签和两个按钮组成。 您几乎可以用某种方式谈论某种自制桌子。 我知道有现成的表格小部件可用,但我想使用自己的表格小部件。
我想要实现的是:当我单击其中一个小部件中的“向上”按钮时,它应该向上移动,或者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;
}
同意CE Gesser,在布局中没有用于布局项目的界面,例如“ setIndex”。
如果您要实现象棋盘上的象棋这样的应用程序,其中移动小部件经常运行,则QGraphicsView + QGraphicsItem(即QWidgetItem)可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.