如何在QWidget中创建QToolBar?

njp*_*wal 3 c++ qt qtoolbar

我想添加QToolBar一个QWidget。但是我希望它的功能像它一样工作QMainWindow

显然我无法QToolBar在中创建QWidget,并且使用setAllowedAreas不适用于QWidget:它仅适用于QMainWindow。另外,我QWidget在中QMainWindow

如何QToolBar为小部件创建一个?

Jon*_*per 5

allowedAreas属性仅在工具栏是的子级时起作用QMainWindow。您可以将工具栏添加到布局中,但用户无法移动它。但是,您仍然可以通过编程方式将其重新放置。

要将其添加到虚拟类继承的布局中QWidget

void SomeWidget::setupWidgetUi()
{
    toolLayout = new QBoxLayout(QBoxLayout::TopToBottom, this);
    //set margins to zero so the toolbar touches the widget's edges
    toolLayout->setContentsMargins(0, 0, 0, 0);

    toolbar = new QToolBar;
    toolLayout->addWidget(toolbar);

    //use a different layout for the contents so it has normal margins
    contentsLayout = new ...
    toolLayout->addLayout(contentsLayout);

    //more initialization here
 }
Run Code Online (Sandbox Code Playgroud)

更改工具栏的方向,需要调用的额外步骤setDirectiontoolbarLayout,例如:

toolbar->setOrientation(Qt::Vertical);
toolbarLayout->setDirection(QBoxLayout::LeftToRight);
//the toolbar is now on the left side of the widget, oriented vertically
Run Code Online (Sandbox Code Playgroud)