Qt使用Splitter调整QMainWindow的大小

时间:2011-11-21 16:38:11

标签: c++ qt resize qsplitter

我有一个QMainWindow:

  • 水平分割器中的两个小部件。 “m_liner”在右侧
    • 两个小部件的最小尺寸为300像素。
  • 隐藏/显示右侧窗口小部件m_liner的复选框。

我希望整体QMainWindow在显示窗口小部件时展开,并在隐藏时收缩。下面的代码执行此操作,除了:

  • 如果显示两个小部件,则最小窗口大小为600像素。
  • 将窗户缩小到最小尺寸。
  • 取消选中该框以隐藏右侧小部件。
  • 程序会隐藏右侧窗口小部件。
  • 程序调用this-> resize(300,height);
  • 窗口最终宽度为600像素(两个窗口小部件都可见的最小尺寸),而不是大约300(仅限左侧窗口小部件的最小尺寸)。
  • 稍后,我可以使用鼠标或其他按钮将窗口调整为300像素。但是在复选框事件中它不会调整为300,即使我多次调用resize。

有没有人知道如何解决这个问题?

关键代码如下:如果需要,我有一个完整的项目:

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

1 个答案:

答案 0 :(得分:1)

听起来有些内部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() );

再次显示小部件时,您需要再次调整大小政策。

相关问题