【QT】C++ GUI Qt4 学习笔记3

菜单界面的实现。

看书上第三章,好长,好多代码。我敲了半天,想看看效果,结果却显示不出来。仔细一看,发现spreadsheet的实现在第四章。郁闷....

又到官网上下代码,结果居然不能运行。难道是因为我的版本太高了?

只好自己改,把没实现的部分都先忽略掉,即忽略掉具体的功能,只是显示菜单。折腾了半天,搞定了。

总结一下:

创建菜单:

需要再主窗口类中声明

1.QMenu * 代表一个菜单

2.QAction * 代表菜单中的一个动作 一般一个菜单里会有很多歌动作

3.每个动作对应的槽函数

然后在实现中:

QMenu 的创建,拿fileMenu举例:

主要是1.在窗口中生成菜单 2.添加动作

//文件菜单
    fileMenu = menuBar()->addMenu(tr("&File")); //设置显示的名称
    fileMenu->addAction(newAction); //添加动作
    fileMenu->addAction(openAction);
    fileMenu->addAction(saveAction);
    fileMenu->addAction(saveAsAction);
    separatorAction = fileMenu->addSeparator(); //插入间隔器
    for(int i = 0; i < MaxRecentFiles; i++)
    {
        fileMenu->addAction(recentFileActions[i]);
    }
    fileMenu->addSeparator();
    fileMenu->addAction(exitAction);

QAction 的创建,主要包括:

1.新建动作

2.设置动作的图标

3.设置快捷键

4.设置提示 (好奇怪,我设置的提示都显示不出来)

5.添加信号和槽的连接

拿newAction举例:

    newAction = new QAction(tr("&New"),this);
    newAction->setIcon(QIcon(":file/images/icon.jpg"));
    newAction->setShortcut(QKeySequence::New); //有标准化序列的 没有就用 tr("Ctrl + Q") 之类的
    newAction->setStatusTip(tr("Create a new spreadsheet file"));
    connect(newAction, SIGNAL(triggered()),this, SLOT(newFile()));

功能函数:

由于只看看样子,都设成空函数就好了。

创建工具栏:

需要声明 QToolBar *

需要的动作和上面是一样的

创建:

    fileToolBar = addToolBar(tr("&File"));
    fileToolBar->addAction(newAction);
    fileToolBar->addAction(openAction);
    fileToolBar->addAction(saveAction);

创建状态栏:

用 QLabel

代码如下:

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "finddialog.h"
#include "gotocelldialog.h"
#include "sortdialog.h"

MainWindow::MainWindow()
{
    //spreadsheet = new Spreadsheet;
    //setCentralWidget(spreadsheet); //设置sheet为主窗口的中央窗口

    //创建主窗口的其他部分

    createActions();
    createMenus();
    //createContextMenu();
    createToolBars();
    //createStatusBar();
    //读取应用程序存储的设置
    //readSettings();
    //find 初始化为空指针
    //findDialog = 0;

    setWindowIcon(QIcon(":file/images/icon.jpg"));
    //setCurrentFile("");
}

void MainWindow::createActions()
{
    /**************File 菜单动作创建***************************/
    //新建
    newAction = new QAction(tr("&New"),this);
    newAction->setIcon(QIcon(":file/images/icon.jpg"));
    newAction->setShortcut(QKeySequence::New);
    newAction->setStatusTip(tr("Create a new spreadsheet file"));
    connect(newAction, SIGNAL(triggered()),this, SLOT(newFile()));
    //打开
    openAction = new QAction(tr("&Open"),this);
    openAction->setIcon(QIcon(":file/images/icon.jpg"));
    openAction->setShortcut(QKeySequence::Open);
    openAction->setStatusTip(tr("Open a file"));
    connect(openAction, SIGNAL(triggered()),this, SLOT(open()));
    //保存
    saveAction = new QAction(tr("&Save"),this);
    saveAction->setIcon(QIcon(":file/images/icon.jpg"));
    saveAction->setShortcut(QKeySequence::Save);
    saveAction->setStatusTip(tr("Save the file"));
    connect(saveAction, SIGNAL(triggered()),this, SLOT(save()));
    //另存为
    saveAsAction = new QAction(tr("&Save As"),this);
    saveAsAction->setIcon(QIcon(":file/images/icon.jpg"));
    saveAsAction->setShortcut(QKeySequence::SaveAs);
    saveAsAction->setStatusTip(tr("Save the file As"));
    connect(saveAsAction, SIGNAL(triggered()),this, SLOT(saveAs()));
    //最近打开的文件

    for(int i = 0; i < MaxRecentFiles; i++)
    {
        recentFileActions[i] = new QAction(this);
        recentFileActions[i]->setVisible(false);
        connect(recentFileActions[i], SIGNAL(triggered()),this,SLOT(openRecentFile()));
    }

    //退出
    exitAction = new QAction(tr("E&xit"),this);
    exitAction->setShortcut(tr("Ctrl+Q"));//没有终止程序的标准化序列键 需要明确指定
    exitAction->setStatusTip(tr("Exit the application"));
    connect(exitAction, SIGNAL(triggered()),this,SLOT(close()));

    /********************Edit 菜单动作创建***************************/
    cutAction = new QAction(tr("Cu&t"), this);
    cutAction->setIcon(QIcon(":file/images/icon.jpg"));
    cutAction->setShortcut(QKeySequence::Cut);
    cutAction->setStatusTip(tr("Cut the current selection‘s contents "
                               "to the clipboard"));
   // connect(cutAction, SIGNAL(triggered()), spreadsheet, SLOT(cut()));

    copyAction = new QAction(tr("&Copy"), this);
    copyAction->setIcon(QIcon(":file/images/icon.jpg"));
    copyAction->setShortcut(QKeySequence::Copy);
    copyAction->setStatusTip(tr("Copy the current selection‘s contents "
                                "to the clipboard"));
   // connect(copyAction, SIGNAL(triggered()), spreadsheet, SLOT(copy()));

    pasteAction = new QAction(tr("&Paste"), this);
    pasteAction->setIcon(QIcon(":file/images/icon.jpg"));
    pasteAction->setShortcut(QKeySequence::Paste);
    pasteAction->setStatusTip(tr("Paste the clipboard‘s contents into "
                                 "the current selection"));
   // connect(pasteAction, SIGNAL(triggered()),
   //        spreadsheet, SLOT(paste()));

    deleteAction = new QAction(tr("&Delete"), this);
    deleteAction->setShortcut(QKeySequence::Delete);
    deleteAction->setStatusTip(tr("Delete the current selection‘s "
                                  "contents"));
    //connect(deleteAction, SIGNAL(triggered()),
    //        spreadsheet, SLOT(del()));

    //全选
    selectAllAction = new QAction(tr("&All"),this);
    selectAllAction->setShortcut(QKeySequence::SelectAll);
    selectAllAction->setStatusTip(tr("Select all the cells in the ‘spreadsheet‘"));
    connect(selectAllAction, SIGNAL(triggered()),this, SLOT(selectAll())); //Qt已经实现了全选

    selectRowAction = new QAction(tr("&Row"), this);
    selectRowAction->setStatusTip(tr("Select all the cells in the "
                                     "current row"));
    //connect(selectRowAction, SIGNAL(triggered()),
    //        spreadsheet, SLOT(selectCurrentRow()));

    selectColumnAction = new QAction(tr("&Column"), this);
    selectColumnAction->setStatusTip(tr("Select all the cells in the "
                                        "current column"));
    //connect(selectColumnAction, SIGNAL(triggered()),
    //        spreadsheet, SLOT(selectCurrentColumn()));

    findAction = new QAction(tr("&Find..."), this);
    findAction->setIcon(QIcon(":file/images/icon.jpg"));
    findAction->setShortcut(QKeySequence::Find);
    findAction->setStatusTip(tr("Find a matching cell"));
    connect(findAction, SIGNAL(triggered()), this, SLOT(find()));

    goToCellAction = new QAction(tr("&Go to Cell..."), this);
    goToCellAction->setIcon(QIcon(":file/images/icon.jpg"));
    goToCellAction->setShortcut(tr("Ctrl+G"));
    goToCellAction->setStatusTip(tr("Go to the specified cell"));
    connect(goToCellAction, SIGNAL(triggered()),
            this, SLOT(goToCell()));

    /********************Tools 菜单动作创建***************************/
    recalculateAction = new QAction(tr("&Recalculate"), this);
    recalculateAction->setShortcut(tr("F9"));
    recalculateAction->setStatusTip(tr("Recalculate all the "
                                       "spreadsheet‘s formulas"));
   // connect(recalculateAction, SIGNAL(triggered()),
   //        spreadsheet, SLOT(recalculate()));

    sortAction = new QAction(tr("&Sort..."), this);
    sortAction->setStatusTip(tr("Sort the selected cells or all the "
                                "cells"));
   // connect(sortAction, SIGNAL(triggered()), this, SLOT(sort()));

   /********************options 菜单动作创建***************************/
    //显示网格  用切换按钮 toggle
    showGridAction = new QAction(tr("&Show Grid"),this);
    showGridAction->setCheckable(true);
    //showGridAction->setChecked(spreadsheet->showGrid());
    showGridAction->setStatusTip(tr("Show or hide the spreadsheet‘s grid"));
    //connect(showGridAction, SIGNAL(toggled(bool)),this, SLOT(setShowGrid(bool)));

    autoRecalcAction = new QAction(tr("&Auto-Recalculate"), this);
    autoRecalcAction->setCheckable(true);
    //autoRecalcAction->setChecked(spreadsheet->autoRecalculate());
    autoRecalcAction->setStatusTip(tr("Switch auto-recalculation on or "
                                      "off"));
    //connect(autoRecalcAction, SIGNAL(toggled(bool)),
    //        spreadsheet, SLOT(setAutoRecalculate(bool)));

    aboutAction = new QAction(tr("&About"), this);
    aboutAction->setStatusTip(tr("Show the application‘s About box"));
    //connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));

    aboutQtAction = new QAction(tr("About &Qt"), this);
    aboutQtAction->setStatusTip(tr("Show the Qt library‘s About box"));
    //connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}

void MainWindow::createMenus()
{
    //文件菜单
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(newAction);
    fileMenu->addAction(openAction);
    fileMenu->addAction(saveAction);
    fileMenu->addAction(saveAsAction);
    separatorAction = fileMenu->addSeparator(); //插入间隔器
    for(int i = 0; i < MaxRecentFiles; i++)
    {
        fileMenu->addAction(recentFileActions[i]);
    }
    fileMenu->addSeparator();
    fileMenu->addAction(exitAction);

    //编辑菜单
    editMenu = menuBar()->addMenu(tr("&Edit"));
    editMenu->addAction(cutAction);
    editMenu->addAction(copyAction);
    editMenu->addAction(pasteAction);
    editMenu->addAction(deleteAction);
    selectSubMenu = editMenu->addMenu(tr("&Select")); //edit菜单的子菜单
    selectSubMenu->addAction(selectRowAction);
    selectSubMenu->addAction(selectColumnAction);
    selectSubMenu->addAction(selectAllAction);
    editMenu->addSeparator();
    editMenu->addAction(findAction);
    editMenu->addAction(goToCellAction);

    //工具菜单
    toolsMenu = menuBar()->addMenu(tr("&Tools"));
    toolsMenu->addAction(recalculateAction);
    toolsMenu->addAction(sortAction);

    //options 菜单
    optionsMenu = menuBar()->addMenu(tr("&Options"));
    optionsMenu->addAction(showGridAction);
    optionsMenu->addAction(autoRecalcAction);

    menuBar()->addSeparator();

    //help 菜单
    helpMenu = menuBar()->addMenu(tr("&Help"));
    helpMenu->addAction(aboutAction);
    helpMenu->addAction(aboutQtAction);
}

void MainWindow::createToolBars()
{
    fileToolBar = addToolBar(tr("&File"));
    fileToolBar->addAction(newAction);
    fileToolBar->addAction(openAction);
    fileToolBar->addAction(saveAction);

    editToolBar = addToolBar(tr("&Edit"));
    editToolBar->addAction(cutAction);
    editToolBar->addAction(copyAction);
    editToolBar->addAction(pasteAction);
    editToolBar->addSeparator();
    editToolBar->addAction(findAction);
    editToolBar->addAction(goToCellAction);
}

void MainWindow::createStatusBar()
{
    locationLabel = new QLabel(" W999 ");
    locationLabel->setAlignment(Qt::AlignHCenter);
    locationLabel->setMinimumSize(locationLabel->sizeHint());

    formulaLabel = new QLabel;
    formulaLabel->setIndent(3);

    statusBar()->addWidget(locationLabel);
    statusBar()->addWidget(formulaLabel, 1);

    //connect(spreadsheet, SIGNAL(currentCellChanged(int, int, int, int)),
    //        this, SLOT(updateStatusBar()));
    //connect(spreadsheet, SIGNAL(modified()),
    //        this, SLOT(spreadsheetModified()));

    //updateStatusBar();
}

bool MainWindow::okToContinue()
{
    if (isWindowModified()) {
        int r = QMessageBox::warning(this, tr("Spreadsheet"),
                        tr("The document has been modified.\n"
                           "Do you want to save your changes?"),
                        QMessageBox::Yes | QMessageBox::No
                        | QMessageBox::Cancel);
        if (r == QMessageBox::Yes) {
            return save();
        } else if (r == QMessageBox::Cancel) {
            return false;
        }
    }
    return true;
}

void MainWindow::newFile()
{
    if (okToContinue()) {
    }
}

void MainWindow::open()
{
    if (okToContinue()) {
    }
}

bool MainWindow::save()
{
    if (curFile.isEmpty()) {
        return saveAs();
    } else {
        return saveFile(curFile);
    }
}

bool MainWindow::saveAs()
{
    return false;
}

void MainWindow::openRecentFile()
{
}

bool MainWindow::saveFile(const QString &fileName)
{
    return true;
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMessageBox>
class QAction;
class QLabel;
class FindDialog;
class Spreadsheet;

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow();

//protected:
 //   void closeEvent(QCloseEvent * event); //QWidget类中的虚函数 重新实现 可以询问是否保存
private slots:
    void newFile();
    void open();
    bool save();
    bool saveAs();
//    void find();
//    void goToCell();
//    void sort();
//    void about();
    void openRecentFile();
//    void updateStatusBar();
//    void SpreadsheetModified();

private:
    void createActions();
    void createMenus();
//   void createContextMenu();
    void createToolBars();
    void createStatusBar();
//    void readSettings();
//    void writeSettings();
    bool okToContinue();
//    bool loadFile(const QString &fileName);
    bool saveFile(const QString &fileName);
//    void setCurrentFile(const QString &fileName);
//    void updateRecentFileActions();
//    QString strippedName(const QString &fullFileName);

//    Spreadsheet *spreadsheet;
//   FindDialog *findDialog;

//    QStringList recentFiles;
    QString curFile;

    /**********菜单栏*************/
    QMenu *fileMenu;
    QMenu *editMenu;
    QMenu *selectSubMenu;
    QMenu *toolsMenu;
    QMenu *optionsMenu;
    QMenu *helpMenu;
    enum{MaxRecentFiles = 5};
    QAction *recentFileActions[MaxRecentFiles];
    QAction *separatorAction;

    /*********工具栏**********/
    QToolBar * fileToolBar;
    QToolBar * editToolBar;

    /***********状态栏*********/
    QLabel * locationLabel;
    QLabel * formulaLabel;

    //file菜单选项
    QAction * newAction;
    QAction * openAction;
    QAction * saveAction;
    QAction * saveAsAction;
    QAction * exitAction;
    //edit菜单选项
    QAction * cutAction;
    QAction * copyAction;
    QAction * pasteAction;
    QAction * deleteAction;
    QAction * selectColumnAction;
    QAction * selectRowAction;
    QAction * selectAllAction;
    QAction * findAction;
    QAction * goToCellAction;
    //tools菜单选项
    QAction * recalculateAction;
    QAction * sortAction;
    //options菜单选项
    QAction * showGridAction;
    QAction * autoRecalcAction;
    //help菜单选项
    QAction * aboutAction;
    QAction * aboutQtAction;

};

#endif // MAINWINDOW_H

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

效果如下:我偷懒,所有的图标都用同一张图。图是我用processing画的,是匡的第一个拼音K,哈哈。

时间: 2024-08-28 21:35:00

【QT】C++ GUI Qt4 学习笔记3的相关文章

C++ GUI Qt4学习笔记08

C++ GUI Qt4学习笔记08 qtc++signal图形引擎文档 [html] view plaincopy 本章介绍Qt的二维图形引擎,Qt的二维图形引擎是基于QPainter类的.<span style="color:#ff0000;">QPainter既可以绘制几何图形(点.线.矩形等),也可以绘制像素映射.图像和文字.此外QPainter还支持一些高级特性,例如反走样.像素混合.渐变填充和矢量路径等.QPainter也支持线性变换,例如平移.旋转.错切和缩放.

C++ GUI Qt4学习笔记01

C++ GUI Qt4学习笔记01 qtc++signalmakefile文档平台 这一章介绍了如何把基本的C++只是与Qt所提供的功能组合起来创建一些简单的图形用户界面应用程序. 引入两个重要概念:一个是“信号和槽”,另一个是“布局”. 窗口部件(widget)是用户界面的一个可视化元素,相当于windows系统中的“控件”和“容器”.任意窗口部件都可以用作窗口. 1.1Hello Qt 正确安装Qt4开发环境,创建工程目录hello,源代码文件名为hello.cpp,进入hello目录 (1

C++ GUI Qt4学习笔记05

C++ GUI Qt4学习笔记05 qtc++正则表达式 QIntValidator           --  只让用户输入整数 QDoubleValidator     --  只让用户输入浮点数 QRegExpValidator    --  只让用户按照正则表达式定义好的样式进行输入 本章讲解如何使用Qt开发自定义窗口部件. 通过对一个已经存在的Qt窗口部件进行子类化或者直接对QWidget进行子类化,就可以创建自定义窗口部件. 集成自定义窗口到Qt设计师中,这样就可以像使用内置的Qt窗

C++ GUI Qt4学习笔记09

C++ GUI Qt4学习笔记09 qtc++ 本章介绍Qt中的拖放 拖放是一个应用程序内或者多个应用程序之间传递信息的一种直观的现代操作方式.除了剪贴板提供支持外,通常它还提供数据移动和复制的功能. QMimeData是一个可以提供不同格式数据的类. 9.1使拖放生效 拖放操作有两个动作:拖动和放下.Qt窗口部件可以作为拖动点.放下点或者同时作为拖动点和放下点. 9.2支持自定义拖动类型 9.3剪贴板处理技术 多数应用程序都通过某一种或者几种方式来使用Qt的内置剪贴板处理技术. C++ GUI

C++ GUI Qt4学习笔记07

C++ GUI Qt4 qtc++scrollobject编程 事件(event)是由串口系统或者Qt自身产生的,用以响应所发生的各类事情.当用户按下或者松开键盘或者鼠标上的按键时,就可以产生一个键盘或者鼠标事件:当某个窗口第一次显示的时候,就会产生一个绘制事件.用来告知窗口需要重绘制它本身,从而使得该窗口可见. 使用Qt进行编程开发时,基本不需要考虑事件,Qt窗口部件都会发射信号.但是当我们需要编写自己的自定义窗口部件,或者是当我们希望改变已经存在的Qt窗口部件的行为时,事件就变得非常有用了.

C++ GUI Qt4学习笔记03

C++ GUI Qt4学习笔记03 qtc++spreadsheet文档工具resources 本章介绍创建Spreadsheet应用程序的主窗口 1.子类化QMainWindow 通过子类化QMainWindow可以创建一个窗口 图形用户界面(GUI)应用程序通常会使用很多的图片,最常见的为应用程序提供图片的方法是使用Qt的资源机制(resource mechanism) 使用Qt资源系统,必须创建一个资源文件,并且在识别该资源文件的.pro文件中添加一行代码. RESOURCES = spr

【QT】C++ GUI Qt4 学习笔记4

感觉这本书的顺序设计的太不合理了,出现的最多的一句话就是后面会讲.按照使用的顺序讲不行吗?搞得代码都运行不了. 我决定先直接跳到73页,子类化QTableWidgetItem这一节.因为前面功能的实现都依赖于这一部分. 预备知识: C++关键字 mutable: mutalbe的中文意思是“可变的,易变的”,跟constant(既C++中的const)是反义词. 在C++中,mutable也是为了突破const的限制而设置的.被mutable修饰的变量,将永远处于可变的状态,即使在一个const

【QT】C++ GUI Qt4 学习笔记1

Find对话框实现 平台 Qt5.3.2 MinGW4.8.2 注意创建时用QDialog finddialog.h #ifndef FINDDIALOG_H #define FINDDIALOG_H #include <QDialog> #include <QLabel> #include <QCheckBox> #include <QLineEdit> #include <QPushButton> #include <QLayout&g

【QT】C++ GUI Qt4 学习笔记2

Go To Cell 利用QT Desinger做好界面后加入的代码有 gotocelldialog.h #ifndef GOTOCELLDIALOG_H #define GOTOCELLDIALOG_H #include <QDialog> #include "ui_gotocelldialog.h" class GoToCellDialog : public QDialog, public Ui::GoToCellDialog { Q_OBJECT public: Go

【QT】C++ GUI Qt4 学习笔记5

折腾了好几天,终于把这本书的第三章和第四章给看了个大概. 里面的函数调用关系可谓是复杂. 整理了一部分的函数关系如下: cell关系清理 data(role) 返回应该显示的值 或者对齐方式 或者公式 ->value() 单元格的值,如果是旧的就重新获得 值给cachedValue并返回 对输入的以‘开头和 = 开头的做特殊处理 ->formula() 获得单元格的Edit role ->data(Edit role) ->evalExpression() 计算表达式的值 setF