⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 simple-application.html

📁 qtopiaphone英文帮助,用于初学者和开发人员,初学者可以用来学习,开发人员可以用来资料查询.
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<p>The only thing this widget needs to do in its destructor is delete theprinter it created.  All the other objects are child widgets, which Qtwill delete as appropriate.  Simple. <pre>    void ApplicationWindow::newDoc()    {        ApplicationWindow *ed = new ApplicationWindow;        ed-&gt;<a href="qwidget.html#d6a291">setCaption</a>("Qt Example - Application");        ed-&gt;<a href="qmainwindow.html#eb53e3">show</a>();    }</pre><p>This slot, connected to the File->New menu item and the "new file"tool button, simply creates a new ApplicationWindow, sets some sizeand shows it. <pre>    void ApplicationWindow::load()    {        <a href="qstring.html">QString</a> fn = QFileDialog::getOpenFileName( QString::null, QString::null,                                                   this);        if ( !fn.<a href="qstring.html#c62623">isEmpty</a>() )            load( fn );        else            <a href="qmainwindow.html#530937">statusBar</a>()-&gt;message( "Loading aborted", 2000 );    }</pre><p>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 loadsthat file or gives an error message in the status bar.<p>(We give an error message in the status bar since that's lessbothersome.  We could have used a <a href="qmessagebox.html">QMessageBox</a>, but since we assumethe user will notice that no file was loaded, we just use the statusbar, and the user won't need to hit Enter to make some window goaway.) <pre>    void ApplicationWindow::load( const char *fileName )    {        <a href="qfile.html">QFile</a> f( fileName );        if ( !f.<a href="qfile.html#255995">open</a>( IO_ReadOnly ) )            return;            e-&gt;setAutoUpdate( FALSE );        e-&gt;clear();            <a href="qtextstream.html">QTextStream</a> t(&amp;f);        while ( !t.<a href="qtextstream.html#bb145b">eof</a>() ) {            <a href="qstring.html">QString</a> s = t.<a href="qtextstream.html#ae4af4">readLine</a>();            e-&gt;append( s );        }        f.<a href="qfile.html#64e640">close</a>();            e-&gt;setAutoUpdate( TRUE );        e-&gt;repaint();        e-&gt;setEdited( FALSE );        <a href="qwidget.html#d6a291">setCaption</a>( fileName );        <a href="qstring.html">QString</a> s;        s.<a href="qstring.html#926f67">sprintf</a>( "Loaded document %s", fileName );        <a href="qmainwindow.html#530937">statusBar</a>()-&gt;message( s, 2000 );    }</pre><p>This function loads a file into the editor.  It takes care to turn offauto-update of the editor, for faster loading and less flicker.  Whenit's done, it sets the window system caption to the file name anddisplays a success message for two seconds in the status bar. <pre>    void ApplicationWindow::save()    {        if ( filename.isEmpty() ) {            saveAs();            return;        }            <a href="qstring.html">QString</a> text = e-&gt;text();        <a href="qfile.html">QFile</a> f( filename );        if ( !f.<a href="qfile.html#255995">open</a>( IO_WriteOnly ) ) {            <a href="qmainwindow.html#530937">statusBar</a>()-&gt;message( <a href="qstring.html">QString</a>("Could not write to %1").arg(filename),                                  2000 );            return;        }            <a href="qtextstream.html">QTextStream</a> t( &amp;f );        t &lt;&lt; text;        f.<a href="qfile.html#64e640">close</a>();</pre><p>This function saves the current file.  Nothing remarkable in the firstpart. <pre>        e-&gt;setEdited( FALSE );</pre><p>Tell the editor that the contents haven't been edited since the lastsave.  When the user closes the window, ApplicationWindow may want toask "Save?". <pre>        <a href="qwidget.html#d6a291">setCaption</a>( filename );</pre><p>It may be that the document was saved under a different name than thecaption, so we set the window caption just to be sure. <pre>        <a href="qmainwindow.html#530937">statusBar</a>()-&gt;message( <a href="qstring.html">QString</a>( "File %1 saved" ).arg( filename ), 2000 );    }</pre><p>That was all. <pre>    void ApplicationWindow::saveAs()    {        <a href="qstring.html">QString</a> fn = QFileDialog::getSaveFileName( QString::null, QString::null,                                                   this );        if ( !fn.<a href="qstring.html#c62623">isEmpty</a>() ) {            filename = fn;            save();        } else {            <a href="qmainwindow.html#530937">statusBar</a>()-&gt;message( "Saving aborted", 2000 );        }    }</pre><p>This function asks for a new name, saves the document under that name,and implicitly changes the window system caption to the new name.<p><a name="printer"></a> <pre>    void ApplicationWindow::print()    {        const int Margin = 10;        int pageNo = 1;</pre><p>print() is called by the File->Print menu item and the "print" toolbutton.<p>Since we don't want to print to the very edges of the paper, we use alittle margin: 10 points.  And we keep track of the page count. <pre>        if ( printer-&gt;setup(this) ) {               // printer dialog</pre><p>QPrinter::setup() invokes a print dialog, configures the printerobject, 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... <pre>            <a href="qmainwindow.html#530937">statusBar</a>()-&gt;message( "Printing..." );</pre><p>... set a status bar message in case printing takes any time. <pre>            <a href="qpainter.html">QPainter</a> p;            if( !p.<a href="qpainter.html#02ed5d">begin</a>( printer ) )                return;                             // paint on printer                p.<a href="qpainter.html#998df2">setFont</a>( e-&gt;font() );            int yPos        = 0;                    // y position for each line            <a href="qfontmetrics.html">QFontMetrics</a> fm = p.<a href="qpainter.html#73b2e5">fontMetrics</a>();            <a href="qpaintdevicemetrics.html">QPaintDeviceMetrics</a> metrics( printer ); // need width/height                                                    // of printer surface</pre><p>We create a painter for the output, select font, and set up somevariables we'll need. <pre>            for( int i = 0 ; i &lt; e-&gt;numLines() ; i++ ) {</pre><p>For each line in the text editing widget, we want to print it. <pre>                if ( Margin + yPos &gt; metrics.<a href="qpaintdevicemetrics.html#d4fedb">height</a>() - Margin ) {</pre><p>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 newpage. <pre>                    <a href="qstring.html">QString</a> msg( "Printing (page " );                    msg += QString::number( ++pageNo );                    msg += ")...";                    <a href="qmainwindow.html#530937">statusBar</a>()-&gt;message( msg );                    printer-&gt;newPage();             // no more room on this page                    yPos = 0;                       // back to top of page</pre><p>Four lines to tell the user what we're doing, two lines to do it. <pre>                }</pre><p>Okay, now we know there's space for this line. <pre>                p.<a href="qpainter.html#0f088f">drawText</a>( Margin, Margin + yPos,                            metrics.<a href="qpaintdevicemetrics.html#95eb7b">width</a>(), fm.<a href="qfontmetrics.html#e6e380">lineSpacing</a>(),                            ExpandTabs | DontClip,                            e-&gt;textLine( i ) );</pre><p>Use the painter to print it.<p>In Qt, output to printer use the exact same code as output to screen,pixmaps and picture metafiles.  Therefore, we don't call a QPrinterfunction to draw text, we call a QPainter function.  QPainter works onall the output devices and has a device independent API.  Most of itscode is device-independent, too, which means that it's less likelythat your application will have odd bugs.  (If the same code is usedto print as to draw on the screen, it's less likely that you'll haveprinting-only or screen-only bugs.) <pre>                yPos = yPos + fm.<a href="qfontmetrics.html#e6e380">lineSpacing</a>();</pre><p>Keep count of how much of the paper we've used. <pre>            }</pre><p>At this point we've printed all of the text in the editing widget. <pre>            p.<a href="qpainter.html#365784">end</a>();                                // send job to printer            <a href="qmainwindow.html#530937">statusBar</a>()-&gt;message( "Printing completed", 2000 );</pre><p>So we tell the printer to finish off the last page and tell the userthat we're done. <pre>        } else {            <a href="qmainwindow.html#530937">statusBar</a>()-&gt;message( "Printing aborted", 2000 );        }</pre><p>If the user did not want to print (and <a href="qprinter.html#c3cd23">QPrinter::setup()</a> returnedFALSE), we acknowledge that. <pre>    }</pre><p>Tha's all.  We have printed a text document.<p><a name="closeEvent"></a> <pre>    void ApplicationWindow::closeEvent( <a href="qcloseevent.html">QCloseEvent</a>* ce )    {</pre><p>This event get to process window-system close events.  A close eventis subtly different from a hide event: hide may often mean "iconify"but close means that the window is going away for good. <pre>        if ( !e-&gt;edited() ) {            ce-&gt;<a href="qcloseevent.html#7cf66f">accept</a>();            return;        }</pre><p>If the text hasn't been edited, we just accept the event.  The windowwill be closed, and since we used the <code>WDestructiveClose</code> widgetflag, the widget will be deleted. <pre>        switch( <a href="qmessagebox.html#66b7c8">QMessageBox::information</a>( this, "Qt Application Example",                                          "The document has been changed since "                                          "the last save.",                                          "Save Now", "Cancel", "Leave Anyway",                                          0, 1 ) ) {        case 0:            save();            ce-&gt;<a href="qcloseevent.html#7cf66f">accept</a>();            break;        case 1:        default: // just for sanity            ce-&gt;<a href="qcloseevent.html#ee1736">ignore</a>();            break;        case 2:            ce-&gt;<a href="qcloseevent.html#7cf66f">accept</a>();            break;        }    }</pre><p>We know the text has been edited, so we ask the user: What do you wantto do?  If the user wants to save and then exit, we do that.  If theuser wants to not exit, we ignore the close event (there is a chancethat we can't block it but we try).  If the user just wants to exit,abandoning the edits, that's very simple. <pre>    void ApplicationWindow::about()    {        <a href="qmessagebox.html#f6c3cd">QMessageBox::about</a>( this, "Qt Application Example",                            "This example demonstrates simple use of "                            "QMainWindow,\nQMenuBar and QToolBar.");    }        void ApplicationWindow::aboutQt()    {        <a href="qmessagebox.html#b72270">QMessageBox::aboutQt</a>( this, "Qt Application Example" );    }</pre><p>These two slots use ready-made "about" functions to say a little aboutthis program and the GUI toolkit it uses.  (You don't need to providean About Qt in your programs, but if you use Qt for free we'dappreciate it if you tell people what you're using.)<p>That's all.  A complete, almost useful application with nice help.Almost as good as the "editors" some computer vendors have shippedwith their desktops.  In less than 300 lines of code.<p><address><hr><div align="center"><table width="100%" cellspacing="0" border="0"><tr><td>Copyright 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -