C++-GUI-Qt4-编程(第二版)-Chapter-3 创建主窗口_第1页
C++-GUI-Qt4-编程(第二版)-Chapter-3 创建主窗口_第2页
C++-GUI-Qt4-编程(第二版)-Chapter-3 创建主窗口_第3页
C++-GUI-Qt4-编程(第二版)-Chapter-3 创建主窗口_第4页
C++-GUI-Qt4-编程(第二版)-Chapter-3 创建主窗口_第5页
已阅读5页,还剩43页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter3

创建主窗口这一章讲解如何使用Qt创建窗口。在本章的最后部分,你将能够创建一个应用程序的完整用户界面,包括菜单,工具栏,状态栏以及应用程序所需的足够多的对话框Spreadsheep应用程序3.1子类化QMainWindowSpreadsheet的应用程序主窗口和源代码分别放在mainwindow.h和mainwindow.cpp中由于QDialog和QMainWindow都派生自QWidget,所以第二续航中看到的许多创建对话框的技术这里仍然适用首先是mainwindow.hifndefMAINWINDOW_H#defineMAINWINDOW_H#include<QMainWindow>classQAction;classQLabel;classFindDialog;classSpreadsheet;classMainWindow:publicQMainWindow{Q_OBJECTpublic:MainWindow();protected:voidcloseEvent(QCloseEvent*event);privateslots:voidnewFile();voidopen();boolsave();boolsaveAs();voidfind();voidgoToCell();voidsort();voidabout();voidopenRecentFile();voidupdateStatusBar();voidspreadsheetModified();private:voidcreateActions();voidcreateMenus();voidcreateContextMenu();voidcreateToolBars();voidcreateStatusBar();voidreadSettings();voidwriteSettings();boolokToContinue();boolloadFile(constQString&fileName);boolsaveFile(constQString&fileName);voidsetCurrentFile(constQString&fileName);voidupdateRecentFileActions();QStringstrippedName(constQString&fullFileName);Spreadsheet*spreadsheet;FindDialog*findDialog;QLabel*locationLabel;QLabel*formulaLabel;QStringListrecentFiles;QStringcurFile;enum{MaxRecentFiles=5};QAction*recentFileActions[MaxRecentFiles];QAction*separatorAction;QMenu*fileMenu;QMenu*editMenu;...QToolBar*fileToolBar;QToolBar*editToolBar;QAction*newAction;QAction*openAction;...QAction*aboutQtAction;};#endif现在来看看实现文件mainwindow.cpp#include<QtGui>#include"finddialog.h"#include"gotocelldialog.h"#include"mainwindow.h"#include"sortdialog.h"#include"spreadsheet.h"MainWindow::MainWindow(){spreadsheet=newSpreadsheet;setCentralWidget(spreadsheet);createActions();createMenus();createContextMenu();createToolBars();createStatusBar();readSettings();findDialog=0;setWindowIcon(QIcon(":/images/icon.png"));setCurrentFile("");}QMainWindow中的区域分配为应用程序提供图片的方法把图片保存到文件中,并且在运行的时候载入他们把XPM文件包含在源代码中。使用Qt的资源机制这里使用了Qt的资源机制,因为它比运行是载入的方法方便的多使用Qt的资源机制为是利用机制,必须创建一个资源文件,并在工程文件中加入代码:

RESOURCES=spreadsheet.qrc资源文件使用了一种简单的XML文件格式。这里给出的是从已经使用的资源文件中的部分:

<RCC><qresource><file>images/icon.png</file>...<file>images/gotocell.png</file></qresource></RCC>3.2创建菜单和工具栏创建菜单栏的步骤创建并且设置动作创建菜单并且把动作添加到菜单上创建工具栏并且把动作添加到工具栏上动作是使用createActions()创建的voidMainWindow::createActions(){newAction=newQAction(tr("&New"),this);newAction->setIcon(QIcon(":/images/new.png"));newAction->setShortcut(QKeySequence::New);newAction->setStatusTip(tr("Createanewspreadsheetfile"));connect(newAction,SIGNAL(triggered()),this,SLOT(newFile()));...for(inti=0;i<MaxRecentFiles;++i){recentFileActions[i]=newQAction(this);recentFileActions[i]->setVisible(false);connect(recentFileActions[i],SIGNAL(triggered()),this,SLOT(openRecentFile()));}exitAction=newQAction(tr("E&xit"),this);exitAction->setShortcut(tr("Ctrl+Q"));exitAction->setStatusTip(tr("Exittheapplication"));connect(exitAction,SIGNAL(triggered()),this,SLOT(close()));...selectAllAction=newQAction(tr("&All"),this);selectAllAction->setShortcut(QKeySequence::SelectAll);selectAllAction->setStatusTip(tr("Selectallthecellsinthe""spreadsheet"));connect(selectAllAction,SIGNAL(triggered()),spreadsheet,SLOT(selectAll()));...showGridAction=newQAction(tr("&ShowGrid"),this);showGridAction->setCheckable(true);showGridAction->setChecked(spreadsheet->showGrid());showGridAction->setStatusTip(tr("Showorhidethespreadsheet's""grid"));connect(showGridAction,SIGNAL(toggled(bool)),spreadsheet,SLOT(setShowGrid(bool)));...aboutQtAction=newQAction(tr("About&Qt"),this);aboutQtAction->setStatusTip(tr("ShowtheQtlibrary'sAboutbox"));connect(aboutQtAction,SIGNAL(triggered()),qApp,SLOT(aboutQt()));}AboutQt对话框的效果创建包含刚才动作的菜单系统voidMainWindow::createMenus(){fileMenu=menuBar()->addMenu(tr("&File"));fileMenu->addAction(newAction);fileMenu->addAction(openAction);fileMenu->addAction(saveAction);fileMenu->addAction(saveAsAction);separatorAction=fileMenu->addSeparator();for(inti=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"));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);optionsMenu=menuBar()->addMenu(tr("&Options"));optionsMenu->addAction(showGridAction);optionsMenu->addAction(autoRecalcAction);menuBar()->addSeparator();helpMenu=menuBar()->addMenu(tr("&Help"));helpMenu->addAction(aboutAction);helpMenu->addAction(aboutQtAction);}创建出的菜单的效果上下文菜单的创建voidMainWindow::createContextMenu(){spreadsheet->addAction(cutAction);spreadsheet->addAction(copyAction);spreadsheet->addAction(pasteAction);spreadsheet->setContextMenuPolicy(Qt::ActionsContextMenu);}创建工具栏voidMainWindow::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);}创建状态栏voidMainWindow::createStatusBar(){locationLabel=newQLabel("W999");locationLabel->setAlignment(Qt::AlignHCenter);locationLabel->setMinimumSize(locationLabel->sizeHint());formulaLabel=newQLabel;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();}3.4实现file菜单voidMainWindow::newFile(){if(okToContinue()){spreadsheet->clear();setCurrentFile("");}}boolMainWindow::okToContinue(){if(isWindowModified()){intr=QMessageBox::warning(this,tr("Spreadsheet"),tr("Thedocumenthasbeenmodified.\n""Doyouwanttosaveyourchanges?"),QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);if(r==QMessageBox::Yes){returnsave();}elseif(r==QMessageBox::Cancel){returnfalse;}}returntrue;}QMessageBox介绍QMessageBox提供了许多标准按钮,并且会自动尝试这让其中的一个成为默认的确认按钮除了warining()外,还提供了information(),question(),critical()实现openvoidMainWindow::open(){if(okToContinue()){QStringfileName=QFileDialog::getOpenFileName(this,tr("OpenSpreadsheet"),".",tr("Spreadsheetfiles(*.sp)"));if(!fileName.isEmpty())loadFile(fileName);}}loadfileboolMainWindow::loadFile(constQString&fileName){if(!spreadsheet->readFile(fileName)){statusBar()->showMessage(tr("Loadingcanceled"),2000);returnfalse;}setCurrentFile(fileName);statusBar()->showMessage(tr("Fileloaded"),2000);returntrue;}saveandsaveasboolMainWindow::save(){if(curFile.isEmpty()){returnsaveAs();}else{returnsaveFile(curFile);}}boolMainWindow::saveFile(constQString&fileName){if(!spreadsheet->writeFile(fileName)){statusBar()->showMessage(tr("Savingcanceled"),2000);returnfalse;}setCurrentFile(fileName);statusBar()->showMessage(tr("Filesaved"),2000);returntrue;}setCurrentFilevoidMainWindow::setCurrentFile(constQString&fileName){curFile=fileName;setWindowModified(false);QStringshownName=tr("Untitled");if(!curFile.isEmpty()){shownName=strippedName(curFile);recentFiles.removeAll(curFile);recentFiles.prepend(curFile);updateRecentFileActions();}setWindowTitle(tr("%1[*]-%2").arg(shownName).arg(tr("Spreadsheet")));}QStringMainWindow::strippedName(constQString&fullFileName){returnQFileInfo(fullFileName).fileName();}更新file中的那些条目voidMainWindow::updateRecentFileActions(){QMutableStringListIteratori(recentFiles);while(i.hasNext()){if(!QFile::exists(i.next()))i.remove();}for(intj=0;j<MaxRecentFiles;++j){if(j<recentFiles.count()){QStringtext=tr("&%1%2").arg(j+1).arg(strippedName(recentFiles[j]));recentFileActions[j]->setText(text);recentFileActions[j]->setData(recentFiles[j]);recentFileActions[j]->setVisible(true);}else{recentFileActions[j]->setVisible(false);}}separatorAction->setVisible(!recentFiles.isEmpty());}带最近打开文件列表的file菜单3.5使用对话框这一届说明如何在qt中使用对话框——如何创建,初始化以及运行他们,并且对用户交互作出响应利用了在第二章中创建好的对话框Find对话框的实现voidMainWindow::find(){if(!findDialog){findDialog=newFindDialog(this);connect(findDialog,SIGNAL(findNext(constQString&,Qt::CaseSensitivity)),spreadsheet,SLOT(findNext(constQString&,Qt::CaseSensitivity)));connect(findDialog,SIGNAL(findPrevious(constQString&,Qt::CaseSensitivity)),spreadsheet,SLOT(findPrevious(constQString&,Qt::CaseSensitivity)));}findDialog->show();findDialog->raise();findDialog->activateWindow();}使用find对话框的几种情况这是用户第一次调用find对话框以前曾将调用过find对话框,但是用户关闭了它以前曾经调用过find对话框,并且现在它还是可见的Gotocell对话框voidMainWindow::goToCell(){GoToCellDialogdialog(this);if(dialog.exec()){QStringstr=dialog.lineEdit->text().toUpper();spreadsheet->setCurrentCell(str.mid(1).toInt()-1,str[0].unicode()-'A');}}voidMainWindow::goToCell(){GoToCellDialog*dialog=newGoToCellDialog(this);if(dialog->exec()){QStringstr=dialog->lineEdit->text().toUpper();spreadsheet->setCurrentCell(str.mid(1).toInt()-1,str[0].unicode()-'A');}deletedialog;}Sort对话框voidMainWindow::sort(){SortDialogdialog(this);QTableWidgetSelectionRangerange=spreadsheet->selectedRange();dialog.setColumnRange('A'+range.leftColumn(),'A'+range.rightColumn());if(dialog.exec()){SpreadsheetComparecompare;compare.keys[0]=dialog.primaryColumnCombo->currentIndex();compare.keys[1]=dialog.secondaryColumnCombo->currentIndex()-1;compare.keys[2]=dialog.tertiaryColumnCombo->currentIndex()-1;compare.ascending[0]=(dialog.primaryOrderCombo->currentIndex()==0);compare.ascending[1]=(dialog.secondaryOrderCombo->currentIndex()==0);compare.ascending[2]=(dialog.tertiaryOrderCombo->currentIndex()==0);spreadsheet->sort(compare);}}排序前后的对比About对话框voidMainWindow::about(){QMessageBox::about(this,tr("AboutSpreadsheet"),tr("<h2>Spreadsheet1.1</h2>""<p>Copyright©2008SoftwareInc.""<p>Spreadsheetisasmallapplicationthat""demonstratesQAction,QMainWindow,QMenuBar,""QStatusBar,QTableWidget,QToolBar,andmanyother""Qtclasses."));}3.6存储设置QT中使用QSetting来记录和保存用户对应用程序的修改,和一些设置本例中使用readSettings()来读取设置,使用writeSettings()来保存设置QSetting会存储应用程序中与特定平台相关的信息。如在Windows中使用注册表Spreadsheet中保存设置的方法voidMainWindow::writeSettings(){QSettingssettings("SoftwareInc.","Spreadsheet");settings.setValue("geometry",saveGeometry());settings.setValue("recentFiles",recentFiles);settings.setValue("showGrid",showGridAction->isChecked());settings.setValue("autoRecalc",autoRecalcAction->isChecked());}voidMainWindow::readSettings(){QSettingssettings("SoftwareInc.","Spreadsheet");restoreGeometry(settings.value("geometry").toByteArray());recentFiles=settings.value("recentFiles").toStringList();updateRecentFileActions();boolshowGrid=settings.value("showGrid",true).toBool();showGridAction->setChecked(showGrid);boolautoRecalc=settings.value("autoRecalc",true).toBool();autoRecalcAction->setChecked(autoRecalc);}3.7多文档Spreadsheet只提供了一个单一的主窗口,并且在同一时间只能处理一个文档如果想实现多文档,只要同时启动多个文档就行了当然,为了使菜单的功能与之对应,必须编写新的Action函数了,程序实现也和原来略有区别多文档的实现#include<QApplication>#include"mainwindow.h"intmain(intargc,char*argv[]){QApplicationapp(argc,argv);MainWindowmainWin;mainWin.show();returnapp.exec();}intmain(intargc,char*argv[]){QApplicationapp(argc,argv);MainWindow*mainWin=newMainWindow;mainWin->show();returnapp.exec

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论