[英]How to create QToolBar in QWidget?
我想在QWidget
添加一個QToolBar
。 但我希望它的功能像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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.