c++qt

How to give headings for each toolbar section in Qt


I need to design a custom tool bar as same as below image. For that I have used following lines of code:

m_ptrFileToolBar = new QToolBar("File",theUi->toolBar);
m_ptrNewAct = new QAction(QIcon(":/res/images/New.png"), tr("&New"), this);
m_ptrNewAct->setShortcuts(QKeySequence::New);
m_ptrNewAct->setStatusTip(tr("Create a new file"));
m_ptrFileToolBar->addAction(m_ptrNewAct);

It is showing only tool bar actions. But I need to give headings to each tool bar section. How do I do it in Qt?

enter image description here


Solution

  • You have to subclass QWidgetAction and reimplement QWidgetAction::createWidget() function

    QWidget *myWidgetAction::createWidget(QWidget *parent)
    {
       QWidget *myWidget = new QWidget(parent);
       QAction *act1 = new QAction(QIcon(":/1.png"),tr("New"),myWidget);
       QAction *act2 = new QAction(QIcon(":/2.png"),tr("Open"),myWidget);
       QAction *act3 = new QAction(QIcon(":/3.png"),tr("Create"),myWidget);
       QToolBar *toolbar = new QToolBar(myWidget);
       toolbar->addAction(act1);
       toolbar->addAction(act2);
       toolbar->addAction(act3);
       QLabel *title = new QLabel("test");
       QGridLayout *grid = new QGridLayout(myWidget);
       myWidget->setLayout(grid);
       grid->addWidget(title,0,0,1,0,Qt::AlignCenter);
       grid->addWidget(toolbar,1,0,1,0,Qt::AlignCenter);
       return myWidget;
    }
    

    Then you can add myWidgetAction object to toolbar

    m_ptrFileToolBar = new QToolBar("File",theUi->toolBar);
    myWidgetAction *widgetAction = new myWidgetAction(this);
    m_ptrFileToolBar->addAction(widgetAction);