今天有空接着Qt创建主窗口File菜单的实现,创建主窗口对于我来说确实有些难度,平时不努力学C/C++,现在从头开始很费劲.现在感慨,书到用时方恨少呀。接下来做一个简单的文本编辑器,给文本编辑器添加信号与槽.前面子类化QMainWindow、菜单栏和工具栏、状态栏都做好了。接下来实现文件菜单的信号与槽的链接。
先实现菜单栏中的菜单栏中文件栏的exit动作和帮助栏中的信号与槽,这是最简单的。帮助栏一个是关于,一个是Qt版本信息。
about要建立创建一个about()函数,用来显现一个带有标题,文本内容的的about消息框,这个about消息框父控件是自己本身。About()函数寻找图标是通过icon()函数查找,作为最后使用的信息图标。这里要用到上一篇QMessageBox创建消息框的知识,而about Qt直接用QApplication调用Qt图形化应用程序的qApp对象来实现,qApp是一个全局指针指的是独立的应用对象。而退出动作也是,直接调用qApp中的closeAllWindows()函数来实现。在mainwindow.h头文件类MainWindow主窗口对象里添加Q_OBJECT信号和槽的一个宏定义。定义一个私有信号槽about()函数,当点击about时,触发触发器发出信号,给链接的制定的about槽函数,然后实现对于主窗口about()函数的功能。点击信号与槽链接在mainwindow.cppC++源文件中定义,运行效果如下:
connect(exitAction, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
void MainWindow::about()
{
QMessageBox::about(this, tr("About Recent Files"),
tr("The <b>Recent Files</b> example demonstrates how to provide a "
"recently used file menu in a Qt application."));
}
接着实现新建文件的功能,其实这个也蛮简单的,在mainwindow.h头文件中声明newFile()函数,在mainwindow.cpp文件中添加信号与槽的链接。
connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));
下面是newFile()函数实现的功能,创建一个主窗口对象,将主窗口对象窗口部件显示出来,当点击new是,触发新建触发器发出信号到指定的槽中,然后调用newFile函数来实现新建一个主窗口功能。当想要关闭所有的主窗口时,先关闭打开的消息框,点击File栏中的exit退出或直接Ctrl+Q即可。
void MainWindow::newFile()
{
MainWindow *other = new MainWindow;
other->show();
}
先定义字符串strippedName()函数,用字符创strippedName函数调用窗口部件设置标题setWindowTitle()函数周围的文件名来缩短排除路径。在函数里面构造一个新的QFileInfo()文件信息函数,获取特定文件的相关信息。该文件包含绝对路径或相对路径。为什么我先定义这个strippedName()函数呢?因为当你创建open()函数这个动作链接信号与槽,都会用到这个函数。依此根据错误提示,找到的最后面的函数就是strippedName()函数。然后根据错误提示,反过来添加其所有满足的函数功能。接着就是创建更新最近文件数据动作updateRecentFileActions()函数,在创建函数前先声明一个枚举类型构造函数,给枚举类型MaxRecentFile赋值。然后定义一个更新文件的指针数组动作变量。在主函数中用createActions()函数中用for循环来记录文件文件,用setVisible()显示文件。最后添加设置setCurrentFile()函数。在声明设置当前文件函数前前,先定义一个字符串变量,curfile.用来获取文件名的字符串变量。接着就可以添加其他功能了,比如打开、另存、保存。如果有剪切、复制、粘贴功能都可以添加。如果有做程序员想法,可以研究一下代码。很难讲的能面面俱全的。接下来实现打开功能,声明一个下载文件函数loadFile()用来判断文件的权限,获取文件名等,然后添加open()函数来实现打开文件,书写代码的顺序已经说了,在头文件声明所要用到的类、函数、对象;在源文件调用函数实现具体功能:
接下来添加保存功能,另存功能是一样道理的。先添加保存文件saveFile()函数,在添加saveAs()函数,在添加save()函数。运行效果如下:
最后实现打开文件的记录功能,在头文件中添加void openRecentFile()信号槽,在源文件中调用openRecentFile()实现具体的功能。然后在createActions()函数中,添加信号与槽的的链接。
mainwindow.h头文件
class MainWindow : public QMainWindow
{
     Q_OBJECT
     
     public:
        MainWindow();
        
        
     private slots:
     void newFile();
     void open();
     void save();
     void saveAs();
     void openRecentFile();
     void about();
     
     private:
     void createActions();
     void createMenus();
     void createToolBars();
     void createStatusBar();
     void saveFile(const QString &fileName);
     void loadFile(const QString &fileName);
     void setCurrentFile(const QString &fileName);
     void updateRecentFileActions();
     QString strippedName(const QString &fullFileName);
     
     QString curFile;
     
     QTextEdit *textEdit;
     QLabel *locationLabel;
     
     
     QMenu *fileMenu;
     QMenu *recentFilesMenu;
     QMenu *helpMenu;
     
     QToolBar *fileToolBar;
     
     QAction *newAction;
     QAction *openAction;
     QAction *saveAction;
     QAction *saveAsAction;
     QAction *exitAction;
     QAction *aboutAction;
     QAction *aboutQtAction;
     QAction *separatorAction;
     
     enum { MaxRecentFiles = 5 };
     QAction *recentFileActions[MaxRecentFiles];
};
mainwindow.cpp源文件
MainWindow::MainWindow()
{
      textEdit = new QTextEdit;
      setCentralWidget(textEdit);
createActions();
      createMenus();
      createToolBars();
      createStatusBar();
setWindowTitle(tr("Text Edit"));
      resize(500, 400);
}
void MainWindow::newFile()
{
     MainWindow *other = new MainWindow;
     other->show();
}
void MainWindow::open()
{
     QString fileName = QFileDialog::getOpenFileName(this);
     if (!fileName.isEmpty())
         loadFile(fileName);
}
void MainWindow::save()
{
     if (curFile.isEmpty())
         saveAs();
     else
         saveFile(curFile);
}
void MainWindow::saveAs()
{
     QString fileName = QFileDialog::getSaveFileName(this);
     if (fileName.isEmpty())
         return;
saveFile(fileName);
}
void MainWindow::openRecentFile()
{
     QAction *action = qobject_cast<QAction *>(sender());
     if (action)
         loadFile(action->data().toString());
}
void MainWindow::about()
{
    QMessageBox::about(this, tr("About Recent Files"),
             tr("The <b>Recent Files</b> example demonstrates how to provide a "
                "recently used file menu in a Qt application."));
}

void MainWindow::createActions()
{
     newAction = new QAction(tr("&New"), this);
     newAction->setIcon(QIcon(":/images/new.png"));
     newAction->setShortcut(tr("Ctrl+N"));
     newAction->setStatusTip(tr("Create a new file"));
     connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));
openAction = new QAction(tr("&Open..."), this);
     openAction->setIcon(QIcon(":/images/open.png"));
     openAction->setShortcut(tr("Ctrl+O"));
     openAction->setStatusTip(tr("Open an existing file"));
     connect(openAction, SIGNAL(triggered()), this, SLOT(open()));
saveAction = new QAction(tr("&Save"), this);
     saveAction->setIcon(QIcon(":/images/save.png"));
     saveAction->setShortcut(tr("Ctrl+S"));
     saveAction->setStatusTip(tr("Save the document to disk"));
     connect(saveAction, SIGNAL(triggered()), this, SLOT(save()));
saveAsAction = new QAction(tr("Save &As..."), this);
     saveAsAction->setStatusTip(tr("Save the document under a new name"));
     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()),qApp,SLOT(closeAllWindows()));
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);
menuBar()->addSeparator();
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);
}
void MainWindow::createStatusBar()
{
    locationLabel = new QLabel(" ready ");
    locationLabel->setAlignment(Qt::AlignHCenter);
    locationLabel->setMinimumSize(locationLabel->sizeHint());
    statusBar()->addWidget(locationLabel);
}
void MainWindow::loadFile(const QString &fileName)
{
     QFile file(fileName);
     if (!file.open(QFile::ReadOnly | QFile::Text)) {
         QMessageBox::warning(this, tr("Recent Files"),
                              tr("Cannot read file %1:\n%2.")
                              .arg(fileName)
                              .arg(file.errorString()));
         return;
     }
QTextStream in(&file);
     QApplication::setOverrideCursor(Qt::WaitCursor);
     textEdit->setPlainText(in.readAll());
     QApplication::restoreOverrideCursor();
setCurrentFile(fileName);
     statusBar()->showMessage(tr("File loaded"), 2000);
}
void MainWindow::saveFile(const QString &fileName)
{
     QFile file(fileName);
     if (!file.open(QFile::WriteOnly | QFile::Text)) {
         QMessageBox::warning(this, tr("Recent Files"),
                              tr("Cannot write file %1:\n%2.")
                              .arg(fileName)
                              .arg(file.errorString()));
         return;
     }
QTextStream out(&file);
     QApplication::setOverrideCursor(Qt::WaitCursor);
     out << textEdit->toPlainText();
     QApplication::restoreOverrideCursor();
setCurrentFile(fileName);
     statusBar()->showMessage(tr("File saved"), 2000);
 }
void MainWindow::setCurrentFile(const QString &fileName)
{
     curFile = fileName;
     if (curFile.isEmpty())
         setWindowTitle(tr("Recent Files"));
     else
         setWindowTitle(tr("%1 - %2").arg(strippedName(curFile))
                                     .arg(tr("Recent Files")));
QSettings settings("Trolltech", "Recent Files Example");
     QStringList files = settings.value("recentFileList").toStringList();
     files.removeAll(fileName);
     files.prepend(fileName);
     while (files.size() > MaxRecentFiles)
         files.removeLast();
settings.setValue("recentFileList", files);
foreach (QWidget *widget, QApplication::topLevelWidgets()) {
         MainWindow *mainWin = qobject_cast<MainWindow *>(widget);
         if (mainWin)
             mainWin->updateRecentFileActions();
     }
}
void MainWindow::updateRecentFileActions()
{
     QSettings settings("Trolltech", "Recent Files Example");
     QStringList files = settings.value("recentFileList").toStringList();
int numRecentFiles = qMin(files.size(), (int)MaxRecentFiles);
for (int i = 0; i < numRecentFiles; ++i) {
         QString text = tr("&%1 %2").arg(i + 1).arg(strippedName(files[i]));
         recentFileActions[i]->setText(text);
         recentFileActions[i]->setData(files[i]);
         recentFileActions[i]->setVisible(true);
     }
     for (int j = numRecentFiles; j < MaxRecentFiles; ++j)
         recentFileActions[j]->setVisible(false);
separatorAction->setVisible(numRecentFiles > 0);
}
QString MainWindow::strippedName(const QString &fullFileName)
{
     return QFileInfo(fullFileName).fileName();
}

嘿嘿...感觉到搞程序的很累...

本文转自 chen138 51CTO博客,原文链接:http://blog.51cto.com/chenboqiang/324957,如需转载请自行联系原作者

Qt 第三章 创建主窗口--实现File菜单相关推荐

  1. PyCharm PyQt5创建主窗口源代码

    一.PyCharm PyQt5创建主窗口基本过程: 1.打开PyCharm,新建工程MyMainTest. 2.按照Tools-External Tools-QtDesigner,打开QT设计界面,创 ...

  2. Chapter34 创建主窗口/实现应用程序功能

    Chapter3&4 创建主窗口/实现应用程序功能 第三章和第四章,书里介绍了一个很复杂的应用程序,叫做Spreadsheet,最终实现了一个类似于Excel的表格软件.我试着写了一下,非常的 ...

  3. Unix/Linux下的Curses库开发指南——第三章curses库窗口

    第3 章 curses 库窗口 3 .1 curses 窗口简介 3.1.1窗口概念 窗口是 curses 库中最重要的一个组件,它实际上是屏幕上的一块矩形区域,在上面我们可以进行各种输出以及操作. ...

  4. CreateMainWindow 创建主窗口属性

    MiniGUI 中的主窗口没有窗口类的概念,应通过初始化一个MAINWINCREATE 结构, 然后调用CreateMainWindow 函数来创建一个主窗口.MAINWINCREATE 结构的成员解 ...

  5. Qt的MDI中多个子窗口响应一个菜单事件的优雅实现(动态slot)

    问题: 用过MFC的人都知道,MDI中,某个菜单或者按钮,在视图中可以添加响应函数,在文档中也可以添加响应函数,在框架中也可以添加它的响应函数,优先级分别是视图.文档.框架,而且MFC自动将消息发给当 ...

  6. linux. qt信号崩溃,【创龙AM4379 Cortex-A9试用体验】之I/O中断异步通知驱动程序+QT捕获Linux系统信号+测试信号通知...

    2.驱动程序 安装字符设备驱动程序开发流程开发. 2.1资源定义 定义按键I/O端口号.I/O中断号,以及字符设备的主设备号变量: #define GPIO_KEY1_PIN_NUM (3*32 + ...

  7. Qt学习之对话框与主窗口的创建

    Qt中的信号与槽机制 qt中槽和普通的C++成员函数几乎是一样的--可以是虚函数,可以被重载,可以是共有的,保护的或者私有的. 槽可以和信号连接在一起,在这种情况下,每当发射这个信号的信号,就会自动调 ...

  8. 在Qt Designer中创建主Windows

    在Qt Designer中创建主Windows 在Qt Designer中创建主Windows 菜单Menus 创建菜单 创建菜单项 工具栏 创建和删除工具栏 添加和删​​除工具栏按钮 动作Actio ...

  9. 计算机word窗口的组成,推计算机等级考试题库:一级MS Office第三章“Word窗口及其组成”(一)...

    小编所收集到的相关计算机等级考试题库:一级MS Office第三章"Word窗口及其组成"的资料 大家要认真阅读哦! Word窗口由标题栏.快速访问工具栏.文件选项卡.功能区.工作 ...

最新文章

  1. 动易SiteFactory CMS自动采集器 V2.0
  2. 【Android】Service几个重要的方法运行在哪个线程
  3. 英文词频统计预备,组合数据类型练习
  4. Hive自定义UDF和聚合函数UDAF
  5. Codeforces Good Bye 2016 题解
  6. SAP Spartacus如何启用B2B feature
  7. rabbitmq实战_RabbitMQ 实战系列之:消息传递
  8. 基于 C# 的 ETL 大数据并行编程
  9. python 笔记(三) 断言(assert)
  10. linux系统sudoers文件夹权限777以及/etc/profile文件修改后无法进入系统问题
  11. 使用EasyRecovery来恢复丢失的视频
  12. OFFICE 2007 SP3后续补丁微软官方下载地址
  13. 6678手册阅读记录
  14. php uv pv,PHP網站流量統計--[pv,uv,ip及$_SERVER]說明
  15. 2020年 Web 开发的最佳编程语言
  16. 《Gans in Action》第一章 对抗神经网络介绍
  17. JavaWeb—静态网页HTML
  18. 笔记本更换内存条图解步骤
  19. [总结]高效能人士的七个习惯
  20. OR青年 | 分布鲁棒优化研究报告

热门文章

  1. python如何返回多个值_python- 如何返回多个值 | 学步园
  2. pe常用软件_验证U盘PE系统,有几款纯净好用
  3. 不符合核销规则条件_1136家建筑企业资质核查不符合条件,复查合格率仅50
  4. java 对象怎么序列化,java对象序列化总结
  5. stm32cubemx生成不了keil工程文件_STM32CubeMX系列教程03_创建并生成代码工程
  6. php框架是不是累赘,PHP框架,伤不起啊,伤不起
  7. 与太原工业学院商讨第十七届全国大学生智能车华北赛区承办事宜
  8. 第十六届全国大学生智能车竞赛全部比赛胜利结束了
  9. Carmaer 500W 逆变器初步测试
  10. 2021年春季学期-信号与系统-第四次作业参考答案-第一小题