如何在窗口构造函数之外的QMenuBar中添加一些操作?
我在QtDesigner中使用QMenuBar创建了一些ui_menu.h
文件:
#ifndef UI_MENU_H
#define UI_MENU_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QAction *actionTtt;
QWidget *centralwidget;
QMenuBar *menubar;
QMenu *menuViev;
QStatusBar *statusbar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->resize(800, 600);
actionTtt = new QAction(MainWindow);
actionTtt->setObjectName(QStringLiteral("actionTtt"));
centralwidget = new QWidget(MainWindow);
centralwidget->setObjectName(QStringLiteral("centralwidget"));
MainWindow->setCentralWidget(centralwidget);
menubar = new QMenuBar(MainWindow);
menubar->setObjectName(QStringLiteral("menubar"));
menubar->setGeometry(QRect(0, 0, 800, 21));
menuViev = new QMenu(menubar);
menuViev->setObjectName(QStringLiteral("menuFile"));
MainWindow->setMenuBar(menubar);
statusbar = new QStatusBar(MainWindow);
statusbar->setObjectName(QStringLiteral("statusbar"));
MainWindow->setStatusBar(statusbar);
menubar->addAction(menuFile->menuAction());
menuViev->addAction(actionTtt);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MENU_H
并在menu.cpp
创建该窗口的类:
Menu::Menu(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
}
在这个课程中,我需要一个将QAction添加到QMenuBar
的函数void Menu::AddSubMenu()
{
actionFirst = new QAction(this);
actionFirst->setObjectName("actionFirst");
menuBar->addAction(menuViev->menuAction());
menuViev->addAction(actionFirst);
}
但它显示了以下内容:访问违规读取...
答案 0 :(得分:0)
如果您在menuBar
usnig QtDesigner中创建了菜单“Viev”,那么您不需要这一行:
ui->menuBar->addAction(ui->menuView->menuAction());
此代码适用于我:
void Menu::AddSubMenu()
{
QAction *actionFirst = new QAction(this);
actionFirst->setObjectName("actionFirst");
actionFirst->setText("Test");
ui->menuView->addAction(actionFirst);
}