新手求教Qt的初级问题,关于创建动作的
头文件
#ifndef MAINWINDOW_COPY_H
#define MAINWINDOW_COPY_H
#include <QMainWindow>
class QAction;
class QLabel;
class Spreadsheet;
class MainWindow_copy : public QMainWindow
{
Q_OBJECT
public:
MainWindow_copy();
Spreadsheet *spreadsheet;
public:
QMenu *fileMenu;
QMenu *editMenu;
QMenu *toolsMenu;
QMenu *optionsMenu;
QMenu *helpMenu;
QLabel *locationLabel;
QLabel *formulaLabel;
QToolBar *fileToolBar;
QToolBar *editToolBar;
QAction *newAction;
private:
void createMenus();
void createStatusBar();
void createToolBar();
void createActions();
};
#endif // MAINWINDOW_COPY_H
cpp文件
#include <QMainWindow>
#include <QtGui>
#include <QtGui/QMenuBar>
#include <mainwindow_copy.h>
#include "spreadsheet.h"
MainWindow_copy::MainWindow_copy()
{
createMenus();
spreadsheet = new Spreadsheet;
setCentralWidget(spreadsheet);
createStatusBar();
createToolBar();
}
void MainWindow_copy::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(newAction);
editMenu= menuBar()->addMenu(tr("&Edit"));
toolsMenu = menuBar()->addMenu(tr("&Tools"));
optionsMenu = menuBar()->addMenu(tr("&Options"));
helpMenu = menuBar()->addMenu(tr("&Help"));
}
void MainWindow_copy::createStatusBar()
{
locationLabel = new QLabel("W999");
statusBar()->addWidget(locationLabel);
formulaLabel = new QLabel;
statusBar()->addWidget(formulaLabel,1);
}
void MainWindow_copy::createActions()
{
newAction = new QAction(tr("&New"),this);
newAction->setShortcut(QKeySequence::New);
newAction->setIcon(QIcon(":/images/new.png"));
newAction->setStatusTip("this is a Create new file");
connect(newAction,SIGNAL(triggered()),this,SLOT(close()));
}
主函数
#include <QApplication>
#include "mainwindow_copy.h"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
MainWindow_copy lxb;
lxb.show();
return app.exec();
}
参照经典Qt教程C++ GUI Qt4第三章的例子我想把整个例子再组装一遍,先是创建了窗口,菜单栏,工具栏,还有spreadsheet(上面程序没有包括相关的文件),但是往菜单栏File选项添加动作的时候出现问题了
出现问题的语句: fileMenu->addAction(newAction);
删掉它,窗口正确显示
添上它,提示错误如下:
Starting /home/lxb/qt/mainwindow_copy/mainwindow_copy...
The program has unexpectedly finished.
/home/lxb/qt/mainwindow_copy/mainwindow_copy exited with code 0
我参照示例程序,感觉程序应该没有问题,但是就是报这个错
求高人指点,不胜感激!
[解决办法]
void MainWindow_copy::createMenus(){ fileMenu = menuBar()->addMenu(tr("&File")); createActions();//加上这一句,先创建Action啊,不然action都没有,你怎么添加 fileMenu->addAction(newAction); editMenu= menuBar()->addMenu(tr("&Edit")); toolsMenu = menuBar()->addMenu(tr("&Tools")); optionsMenu = menuBar()->addMenu(tr("&Options")); helpMenu = menuBar()->addMenu(tr("&Help"));}