简体   繁体   English

如何将菜单栏添加到QWidget?

[英]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: 我目前正在使用Qt框架编写C ++应用程序,其中“主窗口”继承自QWidget类:

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? 我应该为我的应用程序使用QMainWindow类而不是QWidget类吗?

It would be easier to use QMainWindow , because it provides a convenient menuBar() method: 使用QMainWindow会更容易,因为它提供了一个方便的menuBar()方法:

QMenuBar* mainMenu = this->menuBar();

But it is possible to add it to QWidget , just as any other widget. 但是可以像其他小部件一样将其添加到QWidget 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. 您可能会发现本教程很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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