【发布时间】:2011-12-19 20:08:05
【问题描述】:
我是 QT 编程新手。我想创建一个带有两个菜单和几个操作的简单菜单栏(FILE 菜单的 3 个操作和 VIEW 菜单的一个操作)。我有 createMenus() 方法,我在其中创建这些菜单和操作,然后将创建的菜单添加到菜单栏,但是当我运行该应用程序时,它没有显示此菜单栏,我不知道为什么。谁能告诉问题是什么?
MainWindow.cpp源码
#include <QtGui>
#include <QAction>
#include "MainWindow.h"
MainWindow::MainWindow() {
// Creeam fereastra principala
QWidget *window = new QWidget;
setCentralWidget(window);
// Creeam eticheta unde vom afisa titlul item-ului selectat
// Implicit va avea un titlu predefinit
infoLabel = new QLabel("Selectati un item va rog ");
createActions();
createMenus();
// Creeam un layout pentru pozitionarea etichetei
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(infoLabel);
window->setLayout(layout);
setWindowTitle("GUI");
setMinimumSize(300, 300);
resize(480,320);
}
void MainWindow::contextMenuEvent(QContextMenuEvent *event) {
QMenu menu(this);
menu.addAction(newAction);
menu.addAction(openAction);
menu.addAction(closeAction);
menu.addAction(preferencesAction);
menu.exec(event->globalPos());
}
void MainWindow::new_() {
infoLabel->setText("A fost selectat : NEW");
}
void MainWindow::open() {
infoLabel->setText("A fost selectat : OPEN");
}
void MainWindow::close() {
}
void MainWindow::preferences() {
infoLabel->setText("A fost selectat : PREFERENCES");
}
void MainWindow::createActions()
{
newAction = new QAction("New", this);
connect(newAction, SIGNAL(triggered()), this, SLOT(new_()));
openAction = new QAction("Open", this);
connect(openAction, SIGNAL(triggered()), this, SLOT(open()));
closeAction = new QAction("Close", this);
connect(closeAction, SIGNAL(triggered()), this, SLOT(close()));
preferencesAction = new QAction("Preferences", this);
connect(preferencesAction, SIGNAL(triggered()), this, SLOT(preferences()));
}
void MainWindow::createMenus()
{
// Creeaza sectiunea File
fileMenu = new QMenu ("File");
// Adauga actiunile new,open si close la sectiunea File
fileMenu->addAction(newAction);
fileMenu->addAction(openAction);
fileMenu->addAction(closeAction);
// Creeaza sectiunea View
viewMenu = new QMenu ("View");
//Adauga actiunea preferences la sectiunea View
viewMenu->addAction(preferencesAction);
menuBar()->addMenu(fileMenu);
menuBar()->addMenu(viewMenu);
}
【问题讨论】:
-
刚刚在 Linux 上使用 Qt 4.5.2 尝试了您的代码,它运行良好。我看不出有什么问题。您使用的是哪个版本的 Qt,您在哪个平台上?
-
我在 MAC OS LION 上使用 QT 4.7.4
-
如果您使用
QMenuBar *menuBar = new QMenuBar(0);并在主窗口中使用setMenuBar(menuBar)安装此菜单,您会得到一个菜单吗?我只提到它作为docs for QMainWindow 提到这应该对Mac 有影响。我知道这当然不是你想做的,只是好奇它是否有效果。 -
游吟诗人,请发表您的评论作为答案,以便可以接受
-
能否上传mainwindow.cpp、mainwindow.h和main.cpp?我有同样的问题,但我不明白你如何回答它:S 当我运行它时,它只显示窗口而不是菜单栏:S
标签: qt4 qt-creator menubar