如何在QWidget中创建QToolBar
How to create QToolBar in QWidget?
我正在尝试在QWidget
中添加QToolBar
。但我希望它的功能像QMainWindow
一样工作。
显然我不能在QWidget
中创建QToolBar
,并且使用setAllowedAreas
不适用于QWidget
:它仅适用于QMainWindow
。另外,我的QWidget
在QMainWindow
.
如何为我的小部件创建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);
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 将设计器中创建的 QWidget 添加到 QToolbar
- 如何在QWidget中创建QToolBar