Qt adds the toolbar to QWidget, qtqwidget
In Qt, It is very convenient to add a toolbar to the main window (QMainWindow class). You can directly use addToolBar, as shown below:
fileToolBar = addToolBar(tr("&File"));fileToolBar->addAction(fileNewAction);fileToolBar->addAction(fileOpenAction);
However, addToolBar is a function of the QMainWindow class. In the QWidget class, there is no function similar to addToolBar to add a toolbar. Therefore, you cannot directly add a toolbar to the QWidget class (subclass of QWidget.
Can I add a toolbar IN THE QWidget class window? Of course. Considering that the toolbar QToolBar is actually a subclass of QWidget (class Q_GUI_EXPORT QToolBar: public QWidget), you can directly add the toolbar to the window as a normal QWidget. Generally, the toolbar is at the top of the window. Therefore, you can take a layout and place the toolbar at the top.
In my example, I want to create a dock-able component box. The corresponding toolbar is displayed above the component box, as shown below:
I. Code excerpt
// 2.1 toolbar compsBoxToolBar = new QToolBar (tr ("component"), dockCompTools); compsBoxToolBar-> setIconSize (QSize (16, 16); compsBoxToolBar-> addAction (compsNewAction ); compsBoxToolBar-> addAction (compsOpenAction); compsBoxToolBar-> addAction (compsSaveAction );... // 2.2 toolkit subject listComp = new XCompListWidget ();... // 2.3 text prompt box QLabel * lbl = new QLabel (this); lbl-> setText (tr ("Component Description:"); txtTipComp = new QTextEdit ();... // 2.4 layout QVBoxLayout * vboxLayout1 = new QVBoxLayout (); toolbar-> addWidget (compsBoxToolBar); // Add the toolbar as a widget to the layout vboxLayout1-> addWidget (listComp ); vboxLayout1-> addWidget (lbl); vboxLayout1-> addWidget (txtTipComp );... // 2.5 application layout QWidget * dockWidgetContents = new QWidget (); dockWidgetContents-> setLayout (vboxLayout1 );
Ii. Result Display