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

📄 index.lxp@lxpwrap=x5925_252ehtm.htm

📁 GUI Programming with Python
💻 HTM
字号:
    <table border="0" cellspacing="0" cellpadding="3" width="100%"><tr><td>    <div align="center" id="bldcontent">      <a href="../default.htm"><img src="../images/opendocs.png" width="63" height="76" border="0"></a>      <br>      <div class="symbol">Your OpenSource Publisher&#153;</div>    </div>      </td></tr></table>    <div align="center" class="author">      	<a href="../products.lxp">Products</a>	&nbsp;|&nbsp;	<a href="../wheretobuy.lxp">Where to buy</a>	&nbsp;|&nbsp;	<a href="../bookstore.lxp">Retailers</a>	&nbsp;|&nbsp;	<a href="../faq.lxp">FAQ</a>	&nbsp;|&nbsp;        <a href="../writeforus.lxp">Write for Us.</a>        &nbsp;|&nbsp;        <a href="#contact">Contact Us.</a>  </div>    <table border="0" cellspacing="3" cellpadding="0" width="100%"><tr><td width="100%">      <div class="content">        <table border="0" cellspacing="2" cellpadding="0" width="100%"><tr><td width="100%">          <div align="center"><H4 CLASS="AUTHOR"><A NAME="AEN5">Boudewijn Rempt</A><br><a href="../../https@secure.linuxports.com/opendocs/default.htm"><img src=odpyqt125.png></a><br>ISBN: 0-97003300-4-4<br><a href="../../https@secure.linuxports.com/opendocs/default.htm">Available from bookstores everywhere or you can order it here.</a><p>You can download the source files for the book <a href="pyqtsrc.tgz">(code / eps) here.</a><hr></div>                    <HTML><HEAD><TITLE>Saving and loading documents</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.72"><LINKREL="HOME"TITLE="GUI Programming with Python: QT Edition"HREF="book1.htm"><LINKREL="UP"TITLE="Creating Application Functionality"HREF="c5783.htm"><LINKREL="PREVIOUS"TITLE="The document"HREF="x5879.htm"><LINKREL="NEXT"TITLE="Undo, redo and other editing functions"HREF="x5968.htm"></HEAD><BODYCLASS="SECT1"BGCOLOR="#FFFFFF"TEXT="#000000"LINK="#0000FF"VLINK="#840084"ALINK="#0000FF"><DIVCLASS="NAVHEADER"><TABLESUMMARY="Header navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><THCOLSPAN="3"ALIGN="center">GUI Programming with Python: QT Edition</TH></TR><TR><TDWIDTH="10%"ALIGN="left"VALIGN="bottom"><A accesskey="P" href="index.lxp@lxpwrap=x5879_252ehtm.htm">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom">Chapter 17. Creating Application Functionality</TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><A accesskey="N" href="index.lxp@lxpwrap=x5968_252ehtm.htm">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="SECT1"><H1CLASS="SECT1">Saving and loading documents</A></H1><P>What's the use of an editor if it can't      load and save texts? It would be of no use at all&#8212; and      thus it is high time that we implemented this essential      functionality. Loading and saving are part of the      <TTCLASS="CLASSNAME">KalamDocument</TT> class. First, we need to      decide if we will make use of the special PyQt file classes, or      of the generic Python file classes. Let's do both for now, and      you can choose which style you prefer.</P><DIVCLASS="SECT2"><H2CLASS="SECT2">Loading</A></H2><P>Loading first:</P><PRECLASS="PROGRAMLISTING">    def open(self, fileName, format=None):        self.setPathName(fileName)        f = QFile(fileName)        if f.exists():            f.open(IO_ReadOnly)            self.setText(QTextStream(f).read())        else:            raise IOError("No such file or directory: '%s'" % fileName)        self._modified=FALSE      </PRE><P>This is the Qt way of doing things:        first, a <TTCLASS="CLASSNAME">QFile</TT> object is created. If a        file with the name <TTCLASS="VARNAME">fileName</TT> already exists,        a <TTCLASS="CLASSNAME">QTextStream</TT> is used to read the text        from the file. This text is read into a        <TTCLASS="CLASSNAME">QString</TT> object, which is passed on to        <TTCLASS="FUNCTION">setText</TT>, which we saw above. If the file        doesn't exist, an exception is raised, which is caught in the        application class, <TTCLASS="CLASSNAME">KalamApp</TT>. </P><P>The Pythonic method is a lot shorter:</P><PRECLASS="PROGRAMLISTING">    def open(self, fileName, format=None):        self.setPathName(fileName)        self.setText(QString(open(str(fileName)).read()))        self._modified=FALSE      </PRE><P>The net result is the same: the document        receives a text in <TTCLASS="CLASSNAME">QString</TT> format, and        all views are updated. There is no appreciable difference in        performance between these two methods, but if you plan to        translate the Python application to C++ at some time, it might        be preferable to work with as many Qt classes as        possible.</P></DIV><DIVCLASS="SECT2"><H2CLASS="SECT2">Saving</A></H2><P>Saving text is slightly more critical        than loading: what you can't load, you can't mangle and lose,        but if the application refuses to save a text, a user can lose        a lot of work. Still, there is little you can do when the disk        is full, beyond preventing the application from crashing. As        long as <SPANCLASS="APPLICATION">Kalam</SPAN> is running, users can still        select, copy and paste text - a lesson I learned with early        versions of Word.  Note that saving using        <TTCLASS="CLASSNAME">QTextStream</TT> is not currently possible.        <TTCLASS="CLASSNAME">QTextStream</TT> uses C++ operator        overloading (i.e. &#60;&#60;) to write to a stream, which is not        yet available in Python.</P><PRECLASS="PROGRAMLISTING">    def save(self, fileName = None, format = None):        if fileName is not None and fileName &#60;&#62; "":            self.setPathName(fileName)        if self.pathName() == None:            raise IOError("Could not save document: no filename.")        if isinstance(self.pathName(), QString):            self.setPathName(str(self.pathName()))        s=str(self.text())        f = open(self.pathName(), "w")        f.write(s)        if s[-1:] != "\n":            f.write("\n")        f.flush()        self._modified = FALSE      </PRE><P>There are a few necessary checks to        perform. The first is to make sure that the document actually        possesses a filename; then we check whether the filename is an        instance of <TTCLASS="CLASSNAME">QString</TT>, instead of a        Python string. Python's file object cannot use        <TTCLASS="CLASSNAME">QString</TT>s &#8212; it needs to have a        genuine Python string. So, if the pathname is an instance of        <TTCLASS="CLASSNAME">QString</TT>, it is converted to a Python        string.</P><P>The document text is then converted to a        Python string. A Python file object is created by using the        <TTCLASS="FUNCTION">open</TT> function, and we write the string to        it. If the last character is not a newline, we write a last        newline and flush the file. It is a good idea to end all files        with a newline, though you may wish to make this is a        user-option in the application.</P></DIV></DIV><DIVCLASS="NAVFOOTER"><HRALIGN="LEFT"WIDTH="100%"><TABLESUMMARY="Footer navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top"><A accesskey="P" href="index.lxp@lxpwrap=x5879_252ehtm.htm">Prev</A></TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><A accesskey="H" href="index.lxp@lxpwrap=book1_252ehtm">Home</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top"><A accesskey="N" href="index.lxp@lxpwrap=x5968_252ehtm.htm">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">The document</TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><A accesskey="U" href="index.lxp@lxpwrap=c5783_252ehtm.htm">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">Undo, redo and other editing functions</TD></TR></TABLE></DIV></BODY></HTML>      </td>      </tr>      </table>      </td>    </tr>  </table>      

⌨️ 快捷键说明

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