我正在尝试在
QToolBar
中添加 QWidget
。但我希望它的功能能够像 QMainWindow
一样工作。
显然我无法在
QToolBar
中创建QWidget
,并且使用setAllowedAreas
不适用于QWidget
:它仅适用于QMainWindow
。另外,我的 QWidget
位于 QMainWindow
中。
如何为我的小部件创建
QToolBar
?
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
}
更改工具栏的方向需要在 setDirection
上调用
toolbarLayout
的额外步骤,例如:
toolbar->setOrientation(Qt::Vertical);
toolbarLayout->setDirection(QBoxLayout::LeftToRight);
//the toolbar is now on the left side of the widget, oriented vertically
QToolBar
是一个小部件。这就是为什么,您可以通过调用 QToolBar
进行布局或通过将 addWidget
父级设置为您的小部件来将 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);
}
在设计器中实际上很容易做到,只需暂时愚弄它,使其认为您的小部件是 QMainWindow。
关闭设计器中的小部件
使用文本编辑器,打开 mywidget.ui 并更改顶部附近的行:
<widget class="QWidget" name="MyWidget">
阅读
<widget class="QMainWindow" name="MyWidget">
保存文件并在 Qt Designer 中重新打开。您现在可以选择添加工具栏。
添加工具栏后,反转该过程,将 mywidget.ui 中的小部件更改回 QWidget。
全部完成,现在您的小部件中就有了一个漂亮的、可视化可编辑的工具栏。