我确实有一个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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句