Search code examples
c++qtqtoolbar

C++ Stretching QLineEdit across center of Toolbar


I four QToolBars which are placed as such:

addToolBar(new BarLeft());
addToolBar(new SearchBar());
addToolBar(new BarRight());
addToolBarBreak();
addToolBar(new BottomBar());

The left bar has a few icons on it. The right one has a few icons on it as well. The center bar contains a text field which I want to stretch 100% between the other two tool bars. QT will automatically stretch the very last toolbar across empty space unless you tell it otherwise. I have found results telling me to do the following, but it has not worked.

SearchBar::SearchBar() {
    setMovable(false);

    editor = new QLineEdit();
    editor->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
    addWidget(editor);
}

The result is that the field fills vertically, but Qt displays nothing to the right of the RightBar, which I have given a fixed width. The result is exactly the same if I flip the policies to be editor->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Expanding);, or if I ommit the enter function call.

For a visual look at what I want to do, just take a look at google chrome, which has a very similar interface:

[ Icon ] [ Icon ] [ ================ Text Field =============== ] [ Icon ] [ Icon ]

My Qt version is 5.2.1


Solution

  • To make one widget grow bigger than others in the same layout, you need horizontal stretch

    editor = new QLineEdit();
    QSizePolicy sp = editor->sizePolicy();
    sp.setHorizontalStretch(1);
    editor->setSizePolicy(sp);
    addWidget(editor);