PyQt FAQ First Programs

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
(Удалено по требованию автора...)
 
Строка 1: Строка 1:
-
In this part of the PyQt4 tutorial we will learn some basic functionality. The explanation will be slow, as if we would talk to a child. The first steps of a child are awkward, so are the very first attempts of a newbie programmer. Remember, there are no stupid people. There are only lazy people and people, that are not persistent enough.
 
-
== Simple example ==
 
-
 
-
The code example is very simplistic. It only shows a small window. Yet we can do a lot with this window. We can resize it. Maximize it. Minimize it. This requires a lot of coding. Someone already coded this functionality. Because it repeats in most applications, there is no need to code it over again So it has  been hidden from a programmer. PyQt is a high level toolkit. If we would code in a lower level toolkit, the following code example could easily have dozens of lines.
 
-
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
 
-
# simple.py
 
-
 
-
import sys
 
-
from PyQt4 import QtGui
 
-
 
-
app = QtGui.QApplication(sys.argv)
 
-
 
-
widget = QtGui.QWidget()
 
-
widget.resize(250, 150)
 
-
widget.setWindowTitle('simple')
 
-
widget.show()
 
-
 
-
sys.exit(app.exec_())
 
-
</source>
 
-
 
-
<source lang="python">
 
-
import sys
 
-
from PyQt4 import QtGui
 
-
</source>
 
-
 
-
Here we provide the necessary imports. The basic GUI widgets are located in <i>QtGui</i> module.
 
-
 
-
<source lang="python">
 
-
app = QtGui.QApplication(sys.argv)
 
-
</source>
 
-
 
-
Every PyQt4 application must create an application object. The application object is located in the QtGui module.
 
-
The <i>sys.argv</i> parameter is a list of arguments from the command line. Python scripts can be run from the shell. It is a way, how we can control the startup of our scripts.
 
-
 
-
<source lang="python">
 
-
widget = QtGui.QWidget()
 
-
</source>
 
-
 
-
The QWidget widget is the base class of all user interface objects in PyQt4. We provide the default constructor for QWidget. The default constructor has no parent. A widget with no parent is called a window.
 
-
 
-
<source lang="python">
 
-
widget.resize(250, 150)
 
-
</source>
 
-
 
-
The <i>resize()</i> method resizes the widget. It is 250px wide and 150px high.
 
-
 
-
<source lang="python">
 
-
widget.setWindowTitle('simple')
 
-
</source>
 
-
 
-
Here we set the title for our window. The title is shown in the titlebar.
 
-
 
-
<source lang="python">
 
-
widget.show()
 
-
</source>
 
-
 
-
The <i>show()</i> method displays the widget on the screen.
 
-
 
-
<source lang="python">
 
-
sys.exit(app.exec_())
 
-
</source>
 
-
 
-
Finally, we enter the mainloop of the application. The event handling starts from this point. The mainloop receives events from the window system and dispatches them to the application widgets. The mainloop ends, if we call the <i>exit()</i> method or the main widget is destroyed. The <i>sys.exit()</i> method ensures a clean exit. The environment will be informed, how the application ended.
 
-
 
-
You wonder why the exec_() method has the underscore? Everything has a meaning. This is obviously because the exec is a python keyword. And thus, exec_() was used instead.
 
-
 
-
[[image: pyqt_faq_simple.jpg | center]]
 
-
 
-
== An application icon ==
 
-
 
-
The application icon is a small image, which is usually displayed in the top left corner of the titlebar. In the following example we will show, how we do it in PyQt4. We will also introduce some new methods.
 
-
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
 
-
# icon.py
 
-
 
-
import sys
 
-
from PyQt4 import QtGui
 
-
 
-
 
-
class Icon(QtGui.QWidget):
 
-
    def __init__(self, parent=None):
 
-
        QtGui.QWidget.__init__(self, parent)
 
-
 
-
        self.setGeometry(300, 300, 250, 150)
 
-
        self.setWindowTitle('Icon')
 
-
        self.setWindowIcon(QtGui.QIcon('icons/web.png'))
 
-
 
-
 
-
app = QtGui.QApplication(sys.argv)
 
-
icon = Icon()
 
-
icon.show()
 
-
sys.exit(app.exec_())
 
-
</source>
 
-
 
-
The previous example was coded in a procedural style. Python programming language supports both procedural and object oriented programming styles. Programming in PyQt4 means programming in OOP.
 
-
 
-
<source lang="python">
 
-
class Icon(QtGui.QWidget):
 
-
    def __init__(self, parent=None):
 
-
        QtGui.QWidget.__init__(self, parent)
 
-
</source>
 
-
 
-
The three most important things in object oriented programming are classes, data and methods. Here we create a new class called Icon. The Icon class inherits from QtGui.QWidget class. This means, that we must call two constructors. The first one for the Icon class and the second one for the inherited class.
 
-
 
-
<source lang="python">
 
-
self.setGeometry(300, 300, 250, 150)
 
-
self.setWindowTitle('Icon')
 
-
self.setWindowIcon(QtGui.QIcon('icons/web.png'))
 
-
</source>
 
-
 
-
All three classes have been inherited from the QtGui.QWidget class. The <i>setGeometry()</i> does two things. It locates the window on the screen and sets the size of the window. The first two parameters are the x and y positions of the window. The third is the width and the fourth is the height of the window. The last method sets the application icon. To do this, we have created a <i>QIcon</i> object. The <i>QIcon</i> receives the path to our icon to be displayed.
 
-
 
-
[[image: pyqt_faq_icon.jpg | center]]
 
-
 
-
== Showing a tooltip ==
 
-
 
-
We can provide a balloon help for any of our widgets.
 
-
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
 
-
# tooltip.py
 
-
 
-
import sys
 
-
from PyQt4 import QtGui
 
-
from PyQt4 import QtCore
 
-
 
-
 
-
class Tooltip(QtGui.QWidget):
 
-
    def __init__(self, parent=None):
 
-
        QtGui.QWidget.__init__(self, parent)
 
-
 
-
        self.setGeometry(300, 300, 250, 150)
 
-
        self.setWindowTitle('Tooltip')
 
-
 
-
        self.setToolTip('This is a &lt;b&gt;QWidget&lt;/b&gt; widget')
 
-
        QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10))
 
-
 
-
 
-
app = QtGui.QApplication(sys.argv)
 
-
tooltip = Tooltip()
 
-
tooltip.show()
 
-
app.exec_()
 
-
 
-
</source>
 
-
 
-
In this example, we show a tooltip for a <i>QWidget</i> widget.
 
-
 
-
<source lang="python">
 
-
self.setToolTip('This is a &lt;b&gt;QWidget&lt;/b&gt; widget')
 
-
 
-
</source>
 
-
 
-
To create a tooltip, we call the <i>setTooltip()</i> method. We can use rich text formatting.
 
-
 
-
<source lang="python">
 
-
QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10))
 
-
</source>
 
-
 
-
Because the default <i>QToolTip</i> font looks bad, we change it.
 
-
 
-
[[image: pyqt_faq_tooltip.jpg | center]]
 
-
 
-
== Closing a window ==
 
-
 
-
The obvious way to how to close a window is to click on the x mark on the titlebar. In the next example, we will show, how we can programatically close our window. We will briefly touch signals and slots.
 
-
 
-
The following is the constructor of a QPushButton, that we will use in our example.
 
-
 
-
<source lang="python">
 
-
  QPushButton(string text, QWidget parent = None)
 
-
</source>
 
-
 
-
The <i>text</i> parameter is a text that will be displayed on the button. The <i>parent</i> is the ancestor, onto which we place our button. In our case it is QWidget.
 
-
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
 
-
# quitbutton.py
 
-
 
-
import sys
 
-
from PyQt4 import QtGui, QtCore
 
-
 
-
 
-
class QuitButton(QtGui.QWidget):
 
-
    def __init__(self, parent=None):
 
-
        QtGui.QWidget.__init__(self, parent)
 
-
 
-
        self.setGeometry(300, 300, 250, 150)
 
-
        self.setWindowTitle('Icon')
 
-
 
-
        quit = QtGui.QPushButton('Close', self)
 
-
        quit.setGeometry(10, 10, 60, 35)
 
-
 
-
        self.connect(quit, QtCore.SIGNAL('clicked()'),
 
-
            QtGui.qApp, QtCore.SLOT('quit()'))
 
-
 
-
 
-
app = QtGui.QApplication(sys.argv)
 
-
qb = QuitButton()
 
-
qb.show()
 
-
sys.exit(app.exec_())
 
-
</source>
 
-
 
-
<source lang="python">
 
-
quit = QtGui.QPushButton('Close', self)
 
-
quit.setGeometry(10, 10, 60, 35)
 
-
</source>
 
-
 
-
We create a push button and position it on the QWidget just like we have positioned the QWidget on the screen.
 
-
 
-
<source lang="python">
 
-
self.connect(quit, QtCore.SIGNAL('clicked()'),
 
-
    QtGui.qApp, QtCore.SLOT('quit()'))
 
-
</source>
 
-
 
-
The event processing system in PyQt4 is built with the signal &amp; slot mechanism. If we click on the button, the signal <i>clicked()</i> is emitted. The slot can be a PyQt slot or any python callable. The <i>QtCore.QObject.connect()</i> method connects signals with slots. In our case the slot is a predefined PyQt <i>quit()</i> slot. The communication is done between two objects. The sender and the receiver. The sender is the push button, the receiver is the application object.
 
-
 
-
[[image: pyqt_faq_quitbutton.jpg | center]]
 
-
 
-
== Message Box ==
 
-
 
-
By default, if we click on the x button on the titlebar, the QWidget is closed. Sometimes we want to modify this default behaviour. For example, if we have a file opened in an editor to which we did some changes. We show a message box to confirm the action.
 
-
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
 
-
# messagebox.py
 
-
 
-
import sys
 
-
from PyQt4 import QtGui
 
-
 
-
 
-
class MessageBox(QtGui.QWidget):
 
-
    def __init__(self, parent=None):
 
-
        QtGui.QWidget.__init__(self, parent)
 
-
 
-
        self.setGeometry(300, 300, 250, 150)
 
-
        self.setWindowTitle('message box')
 
-
 
-
 
-
    def closeEvent(self, event):
 
-
        reply = QtGui.QMessageBox.question(self, 'Message',
 
-
            "Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
 
-
 
-
        if reply == QtGui.QMessageBox.Yes:
 
-
            event.accept()
 
-
        else:
 
-
            event.ignore()
 
-
 
-
app = QtGui.QApplication(sys.argv)
 
-
qb = MessageBox()
 
-
qb.show()
 
-
sys.exit(app.exec_())
 
-
</source>
 
-
 
-
If we close the QWidget, the <i>QCloseEvent</i> is generated. To modify the widget behaviour we need to reimplement the <i>closeEvent()</i> event handler.
 
-
 
-
 
-
<source lang="python">
 
-
reply = QtGui.QMessageBox.question(self, 'Message',
 
-
    "Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
 
-
</source>
 
-
 
-
We show a message box with two buttons. Yes and No. The first string appears on the titlebar. The second string is the message text displayed by the dialog. The return value is stored in the reply variable.
 
-
 
-
<source lang="python">
 
-
if reply == QtGui.QMessageBox.Yes:
 
-
    event.accept()
 
-
else:
 
-
    event.ignore()
 
-
</source>
 
-
 
-
 
-
Here we test the return value. If we clicked Yes button, we accept the event which leads to the closure of the widget and to the termination of the application. Otherwise we ignore the close event.
 
-
 
-
[[image: pyqt_faq_messagebox.jpg | center]]
 
-
 
-
== Centering window on the screen ==
 
-
 
-
The following script shows, how we can center a window on the desktop screen.
 
-
 
-
<source lang="python">
 
-
#!/usr/bin/python
 
-
 
-
# center.py
 
-
 
-
import sys
 
-
from PyQt4 import QtGui
 
-
 
-
 
-
class Center(QtGui.QWidget):
 
-
    def __init__(self, parent=None):
 
-
        QtGui.QWidget.__init__(self, parent)
 
-
 
-
        self.setWindowTitle('center')
 
-
        self.resize(250, 150)
 
-
        self.center()
 
-
 
-
    def center(self):
 
-
        screen = QtGui.QDesktopWidget().screenGeometry()
 
-
        size =  self.geometry()
 
-
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
 
-
 
-
 
-
app = QtGui.QApplication(sys.argv)
 
-
qb = Center()
 
-
qb.show()
 
-
sys.exit(app.exec_())
 
-
</source>
 
-
 
-
<source lang="python">
 
-
self.resize(250, 150)
 
-
</source>
 
-
 
-
Here we resize the QWidget to be 250px wide and 150px heigh.
 
-
 
-
<source lang="python">
 
-
screen = QtGui.QDesktopWidget().screenGeometry()
 
-
</source>
 
-
 
-
We figure out the screen resolution of our monitor.
 
-
 
-
<source lang="python">
 
-
size =  self.geometry()
 
-
</source>
 
-
 
-
Here we get the size of our QWidget.
 
-
 
-
<source lang="python">
 
-
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
 
-
 
-
</source>
 
-
 
-
Here we move the window to the center of the screen.
 
-
 
-
 
-
[[Категория:Qt]]
 
-
[[Категория:Python]]
 

Текущая версия на 11:55, 7 апреля 2009