簡體   English   中英

Qt使用拆分器調整QMainWindow的大小

[英]Qt Resizing a QMainWindow with a Splitter

我有一個QMainWindow與:

  • 水平拆分器中的兩個小部件。 “ m_liner”在右側
    • 這兩個小部件的最小尺寸均為300像素。
  • 一個用於隱藏/顯示右側小部件m_liner的復選框。

我希望整個QMainWindow在顯示小部件時擴展 ,而在隱藏時收縮 下面的代碼執行此操作,除了:

  • 如果同時顯示了兩個小部件,則最小窗口大小為600像素。
  • 將窗口縮小到最小尺寸。
  • 取消選中該框可隱藏右側窗口小部件。
  • 程序隱藏右側窗口小部件。
  • 程序調用this-> resize(300,height);
  • 窗口的最終寬度為600像素(兩個窗口小部件均可見的最小尺寸),而不是300像素(僅左側窗口小部件的最小尺寸)。
  • 稍后,我可以使用鼠標或其他按鈕將窗口縮小到300像素。 但是即使我多次調用resize,它也不會在checkbox事件中調整為300。

有誰知道如何解決這個問題?

關鍵的代碼如下,如果需要,我可以提供完整的項目:

void MainWindow::on_checkBox_stateChanged(int val)
{
std::cout << "-------------------- Checkbox clicked "  << val << std::endl;
bool visible = val;
QWidget * m_liner = ui->textEdit_2;
QSplitter * m_splitter = ui->splitter;

int linerWidth = m_liner->width();
if (linerWidth <= 0) linerWidth = m_lastLinerWidth;
if (linerWidth <= 0) linerWidth = m_liner->sizeHint().width();
// Account for the splitter handle
linerWidth += m_splitter->handleWidth() - 4;

std::cout << "Frame width starts at " << this->width() << std::endl;
std::cout << "Right Panel width is " << m_liner->width() << std::endl;

//  this->setUpdatesEnabled(false);
if (visible && !m_liner->isVisible())
{
  // Expand the window to include the Right Panel
  int w = this->width() + linerWidth;
  m_liner->setVisible(true);
  QList<int> sizes = m_splitter->sizes();
  if (sizes[1] == 0)
  {
    sizes[1] = linerWidth;
    m_splitter->setSizes(sizes);
  }
  this->resize(w, this->height());
}
else if (!visible && m_liner->isVisible())
{
  // Shrink the window to exclude the Right Panel
  int w = this->width() - linerWidth;
  std::cout << "Shrinking to " << w << std::endl;
  m_lastLinerWidth = m_liner->width();
  m_liner->setVisible(false);
  m_splitter->setStretchFactor(1, 0);
  this->resize(w, this->height());
  m_splitter->resize(w, this->height());
  this->update();
  this->resize(w, this->height());
}
else
{
  // Toggle the visibility of the liner
  m_liner->setVisible(visible);
}
this->setUpdatesEnabled(true);
std::cout << "Frame width of " << this->width() << std::endl;
}

在我看來,有些內部Qt事件需要傳播,才能識別您可以調整主窗口的大小。 如果是這種情況,那么我可以想到兩個可能的解決方案:

使用排隊的單次計時器來調用將窗口尺寸減小到300px的代碼:

m_liner->hide();
QTimer::singleShot( 0, this, SLOT(resizeTo300px()) );

或者,在隱藏窗口小部件之后,您可以嘗試調用processEvents()(此函數具有潛在的危險副作用,因此請謹慎使用):

m_liner->hide();
QApplication::processEvents();
resize( w, height() );

另一種可能的解決方案是在隱藏小部件時將其水平尺寸策略設置為忽略:

m_liner->hide();
m_liner->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Preferred );
resize( w, height() );

再次顯示窗口小部件時,您需要再次調整大小策略。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM