📄 index.lxp@lxpwrap=x3738_252ehtm.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™</div> </div> </td></tr></table> <div align="center" class="author"> <a href="../products.lxp">Products</a> | <a href="../wheretobuy.lxp">Where to buy</a> | <a href="../bookstore.lxp">Retailers</a> | <a href="../faq.lxp">FAQ</a> | <a href="../writeforus.lxp">Write for Us.</a> | <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>Qt Utility classes and their Python equivalents</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="Qt Class Hierarchy"HREF="c2591.htm"><LINKREL="PREVIOUS"TITLE="Dialogs and Standard Dialogs"HREF="x3581.htm"><LINKREL="NEXT"TITLE="Qt Designer, BlackAdder and uic"HREF="c4079.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=x3581_252ehtm.htm">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom">Chapter 10. Qt Class Hierarchy</TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><A accesskey="N" href="index.lxp@lxpwrap=c4079_252ehtm.htm">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="SECT1"><H1CLASS="SECT1">Qt Utility classes and their Python equivalents</A></H1><P>A good many of the Qt classes overlap with Python classes. There is <TTCLASS="CLASSNAME">QString</TT>, which offers almost as much functionality as Python's string object and Unicode string object, <TTCLASS="CLASSNAME">QRegExp</TT>, which does the same as Python's <TTCLASS="FILENAME">re</TT> module. Not all Qt classes that overlap with Python classes are available from PyQt, but most are. The defining criterion is usually whether or not such an overlapping class is needed as an argument in method calls.</P><P>In those cases where there is duplication, it is up to you to decide which one to use. If you use as many Qt classes as possible, your application will appear less Pythonic, and will be more difficult to port to other Python gui's. However, it will also be easier to port your Python prototype to fast, compiled C++ code. Thus, it depends on whether you see your Python program as the final goal or as a prototype. It is best to take a firm stand, though — you shouldn't use Qt regular expressions and Python regular expressions in the same program.</P><P>For instance, the dirview Qt example program can use the <TTCLASS="CLASSNAME">QDir</TT> class, or use <TTCLASS="FUNCTION">os.path.walk()</TT>. Compare the following <TTCLASS="FUNCTION">setOpen</TT> functions. The first is a complex script which uses the Qt functions; the second uses <TTCLASS="FUNCTION">setOpen</TT> with the Python equivalents. Both scripts create listview items for all entries in a directory:</P><DIVCLASS="EXAMPLE"></A><P><B>Example 10-18. from dv_qt.py - using Qt utility classes</B></P><PRECLASS="PROGRAMLISTING">#!/usr/bin/env pythonimport sysfrom qt import *class Directory(QListViewItem): def __init__(self, parent, name=None): apply(QListViewItem.__init__,(self,parent)) if isinstance(parent, QListView): self.p = None self.f = '/' else: self.p = parent self.f = name self.c = [] self.readable = 1 def setOpen(self, o): if o and not self.childCount(): s = self.fullName() thisDir = QDir(s) if not thisDir.isReadable(): self.readable = 0 return files = thisDir.entryInfoList() if files: for f in files: fileName = str(f.fileName()) if fileName == '.' or fileName == '..': continue elif f.isSymLink(): d = QListViewItem(self, fileName, 'Symbolic Link') elif f.isDir(): d = Directory(self, fileName) else: if f.isFile(): t = 'File' else: t = 'Special' d = QListViewItem(self, fileName, t) self.c.append(d) QListViewItem.setOpen(self, o) def setup(self): self.setExpandable(1) QListViewItem.setup(self) def fullName(self): if self.p: s = self.p.fullName() + self.f + '/' else: s = '/' return s def text(self, column): if column == 0: return self.f elif self.readable: return 'Directory' else: return 'Unreadable Directory'a = QApplication(sys.argv)mw = QListView()a.setMainWidget(mw)mw.setCaption('Directory Browser')mw.addColumn('Name')mw.addColumn('Type')mw.resize(400, 400)mw.setTreeStepSize(20)root = Directory(mw)root.setOpen(1)mw.show()a.exec_loop() </PRE></DIV><DIVCLASS="EXAMPLE"></A><P><B>Example 10-19. fragment from db_python.py - using Python utility classes</B></P><PRECLASS="PROGRAMLISTING">... def setOpen(self, o): if o and not self.childCount(): s = self.fullName() if (not os.path.isdir(s)): self.readable == 0 return if (not os.access(s, os.F_OK or os.R_OK)): self.readable == 0 return files=os.listdir(s) if files: for fileName in files: f=os.path.join(s, fileName) if fileName == "." or fileName == "..": continue elif os.path.islink(f): d = QListViewItem(self, fileName, 'Symbolic Link') elif os.path.isdir(f): d = Directory(self, fileName) else: if os.path.isfile(f): t = 'File' else: print f t = 'Special' d = QListViewItem(self, fileName, t) self.c.append(d) QListViewItem.setOpen(self, o)... </PRE></DIV><P>The result is the same:</P><DIVCLASS="MEDIAOBJECT"><P><DIVCLASS="CAPTION"><P>The code is different, but the result the same.</P></DIV></P></DIV><P>The first snippet has been taken from the dirview.py example script that comes with PyQt and BlackAdder; the second is my own interpretation of the dirview.cpp example application. Both have been slightly adapted to make them more alike. Perhaps the similarities between the Qt <TTCLASS="CLASSNAME">QDir</TT> object and the Python <TTCLASS="FILENAME">os.path</TT> module are even more striking than the differences.</P><DIVCLASS="SECT2"><H2CLASS="SECT2">High level data structures</A></H2><P>Qt offers a number of custom high-level data structures, where plain C++ is quite primitive in this respect. (Or, at least, C++ was quite primitive in this respect when Qt was first created. Recently, templates and a standard library have been added, and compilers are starting to support these constructs).</P><P>Python already has a dictionary, as well as list and string data structures that are powerful enough for most needs (what Python is missing is an ordered dictionary), so PyQt does not need the Qt high-level data structures, except where they are demanded as parameters in methods.</P><P>Qt has two basic high-level datastructures: arrays and collections. Collections are specialized into dictionaries, lists and maps. You can always use a Python list wherever a <TTCLASS="CLASSNAME">QList</TT> is needed, or a string where a <TTCLASS="CLASSNAME">QByteArray</TT> is needed. In other cases, some methods are not implemented because the datatype is not implemented, as is the case with <TTCLASS="CLASSNAME">QMap</TT>.</P><DIVCLASS="TABLE"></A><P><B>Table 10-1. Qt and Python high-level datastructures</B></P><TABLEBORDER="1"CLASS="CALSTABLE"><THEAD><TR><THALIGN="LEFT"VALIGN="TOP">Qt Class</TH><THALIGN="LEFT"VALIGN="TOP">Python Class</TH><THALIGN="LEFT"VALIGN="TOP">Implemented</TH><THALIGN="LEFT"VALIGN="TOP">Description</TH></TR></THEAD><TBODY><TR><TDALIGN="LEFT"VALIGN="TOP">QArray</TD><TDALIGN="LEFT"VALIGN="TOP">list</TD><TDALIGN="LEFT"VALIGN="TOP">No</TD><TDALIGN="LEFT"VALIGN="TOP">Array of simple types.</TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP">QByteArray</TD><TDALIGN="LEFT"VALIGN="TOP">String</TD><TDALIGN="LEFT"VALIGN="TOP">No</TD><TDALIGN="LEFT"VALIGN="TOP">Use a string wherever a method wants a QByteArray</TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP">QPointArray</TD><TDALIGN="LEFT"VALIGN="TOP">No equivalent</TD><TDALIGN="LEFT"VALIGN="TOP">Yes</TD><TDALIGN="LEFT"VALIGN="TOP">Array of QPoint objects — you can also store QPoint objects in a Python list, of course. </TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP">QCollection</TD><TDALIGN="LEFT"VALIGN="TOP">Dictionary</TD><TDALIGN="LEFT"VALIGN="TOP">No</TD><TDALIGN="LEFT"VALIGN="TOP">Abstract base class for QDict, QList and QMap.</TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP">QDict</TD><TDALIGN="LEFT"VALIGN="TOP">Dictionary</TD><TDALIGN="LEFT"VALIGN="TOP">No</TD><TDALIGN="LEFT"VALIGN="TOP">Just like Python dictionaries, but more complicated in use.</TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP">QList</TD><TDALIGN="LEFT"VALIGN="TOP">list</TD><TDALIGN="LEFT"VALIGN="TOP">No</TD><TDALIGN="LEFT"VALIGN="TOP">Just like Python lists, but more complicated</TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP">QMap</TD><TDALIGN="LEFT"VALIGN="TOP">Dictionary</TD><TDALIGN="LEFT"VALIGN="TOP">No</TD><TDALIGN="LEFT"VALIGN="TOP">Use a Python dictionary — however, when translating a Python prototype to C++, note that a QMap is based on values, not on references; the keys indexing the dictionary are <SPAN><ICLASS="EMPHASIS">copies</I></SPAN> of the original objects, not references.</TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP">QCache</TD><TDALIGN="LEFT"VALIGN="TOP">No equivalent</TD><TDALIGN="LEFT"VALIGN="TOP">No</TD><TDALIGN="LEFT"VALIGN="TOP">A QCache is a low-level class that caches string values so that two variables containing the same text don't use the memory twice. There are similar caches for integers and non-Unicode texts. Python performs the same trick; see the note: Python and Caching.</TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP">QValueList</TD><TDALIGN="LEFT"VALIGN="TOP">list</TD><TDALIGN="LEFT"VALIGN="TOP">No</TD><TDALIGN="LEFT"VALIGN="TOP">A low-level class that implements a list of values (instead of references to objects).</TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP">QVariant</TD><TDALIGN="LEFT"VALIGN="TOP">No equivalent</TD><TDALIGN="LEFT"VALIGN="TOP">Partially</TD><TDALIGN="LEFT"VALIGN="TOP">QVariant is a wrapper class that makes it possible to use C++ as if it were a loosely-typed language (which Python already is). This class is used for implementing class properties (I find it to be a monstrosity compared to Visual Basic's Variant type).</TD></TR></TBODY></TABLE></DIV><DIVCLASS="NOTE"><BLOCKQUOTECLASS="NOTE"><P><B>Python and caching: </B>Python caches certain often-used values and shares those values across variables. Numbers from 0 to 99 (inclusive) are cached, and strings are always cached. Qt uses the same trick from strings and some other objects</P><PRECLASS="SCREEN">Python 2.2a4 (#1, Oct 4 2001, 15:35:57)[GCC 2.95.2 19991024 (release)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> a=1>>> b=1>>> id(a)135268920>>> id(b)135268920>>> a=100>>> b=100>>> id(a)135338528>>> id(b)135338504>>> a="bla">>> b="bla">>> id(a)135563808>>> id(b)1355638 </PRE></BLOCKQUOTE></DIV></DIV><DIVCLASS="SECT2"><H2CLASS="SECT2">Files and other IO</A></H2><P>Qt's file classes include the following:</P><P></P><UL><LI><P>QDir — directory information</P></LI><LI><P>QFile — file handling</P></LI><LI><P>QFileInfo — file information</P></LI><LI><P>QIODevice — abstract IO device</P></LI><LI><P>QBuffer — helper class for buffered IO</P></LI><LI><P>QTextStream — abstract class for text IO</P></LI><LI><P>QTextIStream — text input IO</P></LI><LI><P>QTextOSStream — text output IO</P></LI><LI><P>QAsyncIO — abstract base for asynchronous IO</P></LI><LI><P>QDataSink — asynchronous data consumer</P></LI><LI><P>QDataSource — asynchronous data produced of data</P></LI><LI><P>QDataStream — binary IO</P></LI><LI><P>QIODeviceSource — a datasource that draws data from a QIODevice, like QFile.</P></LI></UL><P>Qt's file and IO handling classes are divided into three groups: classes to handle files on a file system, classes that
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -