简体   繁体   中英

How to add a Menubar to a QWidget?

I am currently writing a C++ Application using the Qt framework, in which the 'main window' inherits from the QWidget class:

class Draughts : public QWidget
{
    Q_OBJECT
public:
    explicit Draughts(QWidget *parent = 0);
    ~Draughts();

private:
    Ui::Draughts *ui;
};

And I attempted to add a simple menu bar to the application, using the following code:

Draughts::Draughts(QWidget *parent) :

    QWidget(parent),
    ui(new Ui::Draughts)
{
    ui->setupUi(this);

    QWidget *menuWidget = new QWidget;

    QMenu *menuGame = new QMenu("Game");
    menuGame->addAction("New");
    menuGame->addAction("Exit");

    QMenu *menuHelp = new QMenu("Help");
    menuHelp->addAction("How to Play...");
    menuHelp->addAction("About");

    //Setup the Application Menu
    QMenuBar mainMenu(this);
    mainMenu.addMenu(menuGame);
    mainMenu.addMenu(menuHelp);
}

Should I be using the QMainWindow class instead of the QWidget class for my application?

It would be easier to use QMainWindow , because it provides a convenient menuBar() method:

QMenuBar* mainMenu = this->menuBar();

But it is possible to add it to QWidget , just as any other widget. Just don't allocate it in the local scope, because it will be deleted after the function finishes. Instead, do it like with other widgets:

QMenuBar mainMenu = new QMenuBar(this);

You should also probably add a layout to your widget, and add the menu to the layout to have more control over where does it appear. You may find this tutorial useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM