我有一个QMainWindow:
我希望整体QMainWindow在显示窗口小部件时展开,并在隐藏时收缩。下面的代码执行此操作,除了:
有没有人知道如何解决这个问题?
关键代码如下:如果需要,我有一个完整的项目:
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;
}
答案 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() );
再次显示小部件时,您需要再次调整大小政策。