如何在QWidget中创建QToolBar

How to create QToolBar in QWidget?

本文关键字:创建 QToolBar QWidget      更新时间:2023-10-16

我正在尝试在QWidget中添加QToolBar。但我希望它的功能像QMainWindow一样工作。

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

如何为我的小部件创建QToolBar

仅当工具栏是QMainWindow的子项时,allowedAreas 属性才有效。您可以将工具栏添加到布局中,但用户无法移动它。但是,您仍可以通过编程方式重新定位它。

要将其添加到继承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
 }

改变工具栏的方向需要在toolbarLayout上调用setDirection的额外步骤,例如:

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

QToolBar是一个小部件。因此,您可以通过为布局调用addWidget或将QToolBar父级设置为小部件来向任何其他小部件添加QToolBar

正如您在QToolBar setAllowedAreas方法的文档中看到的那样:

此属性包含可能放置工具栏的区域。

默认值为 Qt::AllToolBarAreas。

仅当工具栏位于 QMainWindow 中时,此属性才有意义。

这就是为什么如果工具栏不在QMainWindow中,则无法使用setAllowedAreas

据我所知,正确使用工具栏的唯一方法是使用 QMainWindow .

如果要使用工具栏的全部功能,请创建一个带有窗口标志的主窗口 Widget 。通过这种方式,您可以将其添加到其他小部件中,而无需将其显示为新窗口:

class MyWidget : QMainWindow
{
public:
    MyWidget(QWidget *parent);
    //...
    void addToolbar(QToolBar *toolbar);
private:
    QMainWindow *subMW;
}
MyWidget::MyWidget(QWidget *parent)
    QMainWindow(parent)
{
    subMW = new QMainWindow(this, Qt::Widget);//this is the important part. You will have a mainwindow inside your mainwindow
    setCentralWidget(QWidget *parent);
}
void MyWidget::addToolbar(QToolBar *toolbar)
{
    subMW->addToolBar(toolbar);
}