Walkthrough: A Simple ApplicationThis walkthrough shows simple use of QMainWindow, QMenuBar, QPopupMenu, QToolBar and QStatusBar - the classes that every modern application window tends to use. It further shows some use of QWhatsThis (for simple help) and a typical main() using QApplication. Finally, it shows a typical printout function that uses QPrinter.
The declaration of ApplicationWindowHere's the header file in full: /**************************************************************************** ** $Id: //depot/qt/main/examples/application/application.h#5 $ ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** ** This file is part of an example program for Qt. This example ** program may be used, distributed and modified without limitation. ** *****************************************************************************/ #ifndef APPLICATION_H #define APPLICATION_H #include <qmainwindow.h> class QMultiLineEdit; class QToolBar; class QPopupMenu; class ApplicationWindow: public QMainWindow { Q_OBJECT public: ApplicationWindow(); ~ApplicationWindow(); protected: void closeEvent( QCloseEvent* ); private slots: void newDoc(); void load(); void load( const char *fileName ); void save(); void saveAs(); void print(); void about(); void aboutQt(); private: QPrinter *printer; QMultiLineEdit *e; QToolBar *fileTools; QString filename; }; #endif
There's nothing much particular about this. It declares a class that
inherits QMainWindow, with some slots and some private variables. And
it uses a class predeclarations to speed up compiles: The simple main()Here's examples/main.cpp, in full./**************************************************************************** ** $Id: //depot/qt/main/examples/application/main.cpp#4 $ ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** ** This file is part of an example program for Qt. This example ** program may be used, distributed and modified without limitation. ** *****************************************************************************/ #include <qapplication.h> #include "application.h" int main( int argc, char ** argv ) { QApplication a( argc, argv ); ApplicationWindow * mw = new ApplicationWindow(); mw->setCaption( "Qt Example - Application" ); mw->show(); a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) ); return a.exec(); } We'll go over main() in detail. int main( int argc, char ** argv ) { QApplication a( argc, argv ); We create a QApplication object with the usual constructor and let it parse argc and argv so that on X11, this program behaves as X programs are expected to. ApplicationWindow * mw = new ApplicationWindow(); mw->setCaption( "Qt Example - Application" ); mw->show(); We create an ApplicationWindow as a top-level widget, set its window system caption to "Document 1", and show() it.
When the application's last window is closed, it should quit.
Having completed the application initialization, we start the main
event loop (the GUI), and eventually return the error code
QApplication returns when it leaves the event loop.
(QApplication::exit() lets any part of the program set this code in
a way that doesn't prohibit an orderly closedown.)
Since the implementation is much larger (almost 200 lines) we won't
include it in full but instead include bits and pieces as necessary.
We skip the preliminary #include and some text constants, and start
with the constructor.
ApplicationWindow inherits QMainWindow, the Qt class that provides
typical application main windows, with menu bars, tool bars, etc.
The application example can print things, and we chose to have a
QPrinter object lying around so that when the user changes a setting
during one printing, the new setting will be the default next time.
This example is simple enough to have just three commands. These
variables are used to hold the icons for each of them.
We create a tool bar in this window for putting some tools in.
And then we create three tool buttons in that tool bar, each with the
appropriate icons and tool-tip text. The three buttons are connected
to slots in this object, for example the "Print File" button is
connected to ApplicationWindow::print().
Then we create a fourth button in the toolbar: A special button that
provides "What's This?" help. This must be set up using a special
function, as its mouse interface needs to be a little unusual.
We add What's This? help for each of the three buttons, and tell the
QML engine that when a help text wants the "fileopen" image, it should
use the pixmap we've defined.
We create a QPopupMenu item for the File menu, add it to the menu bar,
populate it with three commands, and set What's This? help for them.
Note in particular how What's This? help and pixmaps are used in both
the toolbar (above) and the menu bar (here).
We create a Help menu, add it to the menu bar, and insert a few
commands in the Help menu.
We create a multi-line edit widget, set the initial focus to be there,
and make it the central widget of this window.
QMainWindow::centralWidget() is the meat: It's what the menu bar,
status bar and tool bars are all arranged around. Since this
application is an editor, the central widget is a text editing widget
:)
We make the status bar say "Ready" for two seconds at startup, just to
tell the user that this window has finished initialization and can be
used.
We provide a nice default size for the new window.
That's it.
The only thing this widget needs to do in its destructor is delete the
printer it created. All the other objects are child widgets, which Qt
will delete as appropriate. Simple.
This slot, connected to the File->New menu item and the "new file"
tool button, simply creates a new ApplicationWindow, sets some size
and shows it.
This slot is connected to the "load file" menu item and tool button.
As you can see, it asks the user for a file name and then either loads
that file or gives an error message in the status bar.
(We give an error message in the status bar since that's less
bothersome. We could have used a QMessageBox, but since we assume
the user will notice that no file was loaded, we just use the status
bar, and the user won't need to hit Enter to make some window go
away.)
This function loads a file into the editor. It takes care to turn off
auto-update of the editor, for faster loading and less flicker. When
it's done, it sets the window system caption to the file name and
displays a success message for two seconds in the status bar.
This function saves the current file. Nothing remarkable in the first
part.
Tell the editor that the contents haven't been edited since the last
save. When the user closes the window, ApplicationWindow may want to
ask "Save?".
It may be that the document was saved under a different name than the
caption, so we set the window caption just to be sure.
That was all.
This function asks for a new name, saves the document under that name,
and implicitly changes the window system caption to the new name.
print() is called by the File->Print menu item and the "print" tool
button.
Since we don't want to print to the very edges of the paper, we use a
little margin: 10 points. And we keep track of the page count.
QPrinter::setup() invokes a print dialog, configures the printer
object, and returns TRUE if the user wants to print or FALSE if not.
So, we test the return value, and if it's TRUE, we...
... set a status bar message in case printing takes any time.
We create a painter for the output, select font, and set up some
variables we'll need.
For each line in the text editing widget, we want to print it.
Before we print each line: Is there space for it on the current page,
given the margins we want to use? IF not, we want to start a new
page.
Four lines to tell the user what we're doing, two lines to do it.
Okay, now we know there's space for this line.
Use the painter to print it.
In Qt, output to printer use the exact same code as output to screen,
pixmaps and picture metafiles. Therefore, we don't call a QPrinter
function to draw text, we call a QPainter function. QPainter works on
all the output devices and has a device independent API. Most of its
code is device-independent, too, which means that it's less likely
that your application will have odd bugs. (If the same code is used
to print as to draw on the screen, it's less likely that you'll have
printing-only or screen-only bugs.)
Keep count of how much of the paper we've used.
At this point we've printed all of the text in the editing widget.
So we tell the printer to finish off the last page and tell the user
that we're done.
If the user did not want to print (and QPrinter::setup() returned
FALSE), we acknowledge that.
Tha's all. We have printed a text document.
This event get to process window-system close events. A close event
is subtly different from a hide event: hide may often mean "iconify"
but close means that the window is going away for good.
If the text hasn't been edited, we just accept the event. The window
will be closed, and since we used the
We know the text has been edited, so we ask the user: What do you want
to do? If the user wants to save and then exit, we do that. If the
user wants to not exit, we ignore the close event (there is a chance
that we can't block it but we try). If the user just wants to exit,
abandoning the edits, that's very simple.
These two slots use ready-made "about" functions to say a little about
this program and the GUI toolkit it uses. (You don't need to provide
an About Qt in your programs, but if you use Qt for free we'd
appreciate it if you tell people what you're using.)
That's all. A complete, almost useful application with nice help.
Almost as good as the "editors" some computer vendors have shipped
with their desktops. In less than 300 lines of code.
|
Publicité
Best OfActualités les plus luesSemaine
Mois
Année
Le Qt Developer Network au hasardComment fermer une applicationLe Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.
CommunautéRessources
Liens utilesContact
Qt dans le magazine |
Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. | Qt 2.3 | |
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD. | ||
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP ! |
Copyright © 2000-2012 - www.developpez.com