如何以编程方式更改布局中小部件的顺序? [英] How to programmatically change the order of widgets in a layout?

查看:282
本文介绍了如何以编程方式更改布局中小部件的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QVBoxLayout 包含一些自定义小部件,它们本身主要包括一个标签和两个按钮。你几乎可以说某种自制的桌子在某种程度上。我知道有现成的表格小部件可用,但我想使用自己的。

I do have a QVBoxLayout that contains some custom widgets, which themselves mainly consist of a label and two buttons. You can almost speak of some kind of selfmade table in a way. I know that there are ready-made table widgets available, but I'd like to use my own.

我想要实现的是:当我点击 up按钮,它应该向上移动,或换句话说:它应该改变其在父 QVBoxLayout 中的当前位置/索引每次点击向上(或向下相应)移动一步。那可能吗?我如何实现呢?我需要一个用户友好的方式来设置项目在该布局中的顺序。

What I want to achieve is this: when I click the "up" button in one of the widgets, it should move up, or to put it differently: it should change its current position/index within the parent QVBoxLayout in a way that it moves one step up (or down accordingly) with every click. Is that possible? How can I achieve that? I need that as a user-friendly way to set the order of items within that layout.

我开始尝试从我的窗口小部件中获取父布局:

I began with trying to get the parent layout from within my widget:

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

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

That seems to work, but how to go on from here? Thanks for your help!

推荐答案

您可以尝试这样:

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

这篇关于如何以编程方式更改布局中小部件的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆