首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在QWidget中创建QToolBar?

如何在QWidget中创建QToolBar?
EN

Stack Overflow用户
提问于 2016-07-15 17:16:09
回答 3查看 12.5K关注 0票数 4

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

显然,我不能在QWidget中创建QToolBar,并且使用setAllowedAreas不能与QWidget一起工作:它只能与QMainWindow一起工作。另外,我的QWidgetQMainWindow中。

如何为我的小部件创建QToolBar

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-07-15 17:41:24

只有当工具栏是QMainWindow的子级时,The allowedAreas property才有效。您可以将工具栏添加到布局中,但用户不能移动它。但是,您仍然可以通过编程方式对其进行重新定位。

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

代码语言:javascript
复制
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的额外步骤,例如:

代码语言:javascript
复制
toolbar->setOrientation(Qt::Vertical);
toolbarLayout->setDirection(QBoxLayout::LeftToRight);
//the toolbar is now on the left side of the widget, oriented vertically
票数 8
EN

Stack Overflow用户

发布于 2016-07-15 17:36:10

QToolBar是一个小部件。这就是为什么您可以将QToolBar添加到任何其他小部件,方法是调用addWidget进行布局或将QToolBar父部件设置为您的小部件。

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

此属性保存可能放置工具栏的区域。

默认值为Qt::AllToolBarAreas。

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

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

票数 2
EN

Stack Overflow用户

发布于 2016-07-15 22:19:04

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

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

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38392322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档