2

Qtでうまくいけば明白な機能を備えた折りたたみ/展開ボタンでGroupBoxesを作成しようとしています。ボタンを描画する QGroupBox をサブクラス化しました。クリックすると、コードはsetVisible(false)GroupBox のすべての子を呼び出します。さらに、GroupBox 内のすべての QLayout を調べて、それらの contentMargins をゼロに設定します。ただし、一部の GroupBox は折りたたまれた状態でも他のものよりも大きくなり、何が原因なのかわかりません。

これは私がこれまでに思いついたものです(私は考えられるnullptr問題を認識しています):

void CollapsibleGroupBox::onVisibilityChanged()
{
  CollapseExpandButton::State s;

  s = m_clExpButton->state();

  QLayout *master = this->layout();
  QList<QObject *> children = this->children();

  switch (s) {
  case CollapseExpandButton::State::COLLAPSED:
    for (QObject *o : children) {
      QWidget *w = qobject_cast<QWidget *>(o);
      if (w != nullptr) {
        if (w != m_clExpButton)
          w->setVisible(false);

        continue;
      }

      if (o == master) {
        m_layoutMargins.clear();
        collapseLayout(master);
      }
    }
    break;
  case CollapseExpandButton::State::EXPANDED:
    for (QObject *o : children) {
      QWidget *w = qobject_cast<QWidget *>(o);
      if (w != nullptr) {
        w->setVisible(true);

        continue;
      }

      if (o == master)
        expandLayout(master);

    }
    break;
  }
}


void CollapsibleGroupBox::collapseLayout(QLayout *layout)
{
  for (QObject *o : layout->children()) {
    QLayout *l= qobject_cast<QLayout *>(o);
    if (l == nullptr)
      continue;

    collapseLayout(l);
  }
  if (m_layoutMargins.contains(layout))
    return;

  QMargins m = layout->contentsMargins();
  m_layoutMargins[layout] = m;
  layout->setContentsMargins(0, 0, 0, 0);
}

void CollapsibleGroupBox::expandLayout(QLayout *layout)
{
  for (QObject *o : layout->children()) {
    QLayout *l = qobject_cast<QLayout *>(o);
    if (l == nullptr)
      continue;

    if (m_layoutMargins.contains(l))
      expandLayout(l);
  }
  if (m_layoutMargins.contains(layout)) {
    QMargins m = m_layoutMargins[layout];
    layout->setContentsMargins(m);
  }
}
4

3 に答える 3