2011-11-21 63 views
1

QMainWindow中我有一个的QMainWindow:在水平拆分Qt的调整大小与分配器

  • 两个小部件。 “m_liner”位于右侧
    • 这两个小部件的最小尺寸均为300像素。
  • 用于隐藏/显示右侧窗口小部件m_liner的复选框。

我想整体的QMainWindow到扩大显示widget时,和隐藏时收缩。下面的代码除外:

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

回答

1

像有需要得到传播它认识到,你可以调整之前,一些内部的Qt事件的声音,我主窗口。如果是这样的话,那么我能想到的两种解决办法:

使用排队的单次计时器来调用重新调整你的窗口到300像素的代码:

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()); 

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

+0

谢谢,解决了这个问题!感谢您指出QTimer :: singleShot方法,这将派上用场! –