我正在尝试在QWidget中添加QToolBar。但我希望它的功能能像QMainWindow一样工作。
显然,我不能在QWidget中创建QToolBar,并且使用setAllowedAreas不能与QWidget一起工作:它只能与QMainWindow一起工作。另外,我的QWidget在QMainWindow中。
如何为我的小部件创建QToolBar?
发布于 2016-07-15 17:41:24
只有当工具栏是QMainWindow的子级时,The allowedAreas property才有效。您可以将工具栏添加到布局中,但用户不能移动它。但是,您仍然可以通过编程方式对其进行重新定位。
将其添加到继承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发布于 2016-07-15 17:36:10
QToolBar是一个小部件。这就是为什么您可以将QToolBar添加到任何其他小部件,方法是调用addWidget进行布局或将QToolBar父部件设置为您的小部件。
正如您在QToolBar setAllowedAreas方法文档中所看到的:
此属性保存可能放置工具栏的区域。
默认值为Qt::AllToolBarAreas。
仅当工具栏位于QMainWindow中时,此属性才有意义。
这就是为什么如果工具栏不在QMainWindow中就无法使用setAllowedAreas的原因。
发布于 2016-07-15 22:19:04
据我所知,正确使用工具栏的唯一方法是使用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);
}https://stackoverflow.com/questions/38392322
复制相似问题