4

我正在尝试QToolBarQWidget. 但我希望它的功能能够像QMainWindow.

显然我不能QToolBar在 a中创建QWidget,并且 usingsetAllowedAreas不适用于QWidget:它仅适用于QMainWindow. 另外,我QWidget在一个QMainWindow.

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

4

3 回答 3

8

allowedAreas仅当工具栏是 a 的子级时,属性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
 }

更改工具栏的方向需要调用 的附加步骤setDirectiontoolbarLayout例如:

toolbar->setOrientation(Qt::Vertical);
toolbarLayout->setDirection(QBoxLayout::LeftToRight);
//the toolbar is now on the left side of the widget, oriented vertically
于 2016-07-15T09:41:23.557 回答
2

QToolBar是一个小部件。这就是为什么,您可以通过调用布局或将父级设置为您的小部件来将 a 添加QToolBar到任何其他小部件。addWidgetQToolBar

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

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

默认值为 Qt::AllToolBarAreas。

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

这就是为什么setAllowedAreas如果工具栏不在 QMainWindow 中就无法使用的原因。

于 2016-07-15T09:36:10.440 回答
0

据我所知,正确使用工具栏的唯一方法是使用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);
}
于 2016-07-15T14:19:03.627 回答