Use sublassed QMenuBar as menuBar()



  • Hey there
    I sublassed a QMenuBar:

    // mainmenu.cpp
    #include "mainmenu.h"
    
    Mainmenu::Mainmenu(QWidget *parent) : QMenuBar(parent){
    
        ...
    }
    
    //mainmenu.h
    #include <QWidget>
    #include <QMenuBar>
    
    class Mainmenu : public QMenuBar{
        
        Q_OBJECT
    
        public:
            
            Mainmenu(QWidget *parent = 0);
    };
    
    

    Then I try to use it in a QMainWindow:

    //mainwindow.h
    #include <QMainWindow>
    #include <QMenuBar>
    ...
    #include "mainmenu.h"
    
    class Mainwindow : public QMainWindow {
        
        Q_OBJECT  
    
        public:
        
            Mainwindow(QWidget *parent = 0);
            
        private slots:
            ...
        private:
            ...
            Mainmenu *menu;
    };
    
    
    //mainwindow.cpp
    
    #include "mainwindow.h"
    #include <QVBoxLayout>
    #include <QMenu>
    #include <QAction>
    
    Mainwindow::Mainwindow(QWidget *parent) : QMainWindow(parent){
        ...
        menu = new Mainmenu(this);
        menu = menuBar();
        ...
    }
    
    

    But I get this error when compiling:

    ../sources/mainwindow.cpp: In constructor ‘Mainwindow::Mainwindow(QWidget*)’:
    ../sources/mainwindow.cpp:16:19: error: invalid conversion from ‘QMenuBar*’ to ‘Mainmenu*’ [-fpermissive]
         menu = menuBar();
                ~~~~~~~^~
    make: *** [Makefile:246: object/mainwindow.o] Error 1
    
    

    And I'm not sure what I'm doing wrong
    I want to subclass the menu because it is large (lots of actions/submenus etc),
    and I want to use menuBar() because it is layout-independent



  • menuBar() is the getter, use setMenuBar as setter

    This is a standard pattern in Qt (and C++ in general) methods where you have a method that gets the value and another that sets it


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.