Comenzando con pyqt
Una aplicación básica
El siguiente ejemplo muestra una ventana GUI principal básica con un widget de etiqueta, una barra de herramientas y una barra de estado usando PyQt4.
import sys
from PyQt4 import QtGui
class App(QtGui.QApplication):
def __init__(self, sys_argv):
super(App, self).__init__(sys_argv)
self.build_ui()
def build_ui(self):
# build a main GUI window
self.main_window = QtGui.QMainWindow()
self.main_window.setWindowTitle('App')
self.main_window.show()
# add a label to the main window
label = QtGui.QLabel('Label')
self.main_window.setCentralWidget(label)
# add a toolbar with an action button to the main window
action = QtGui.QAction('Toolbar action', self)
toolbar = QtGui.QToolBar()
toolbar.addAction(action)
self.main_window.addToolBar(toolbar)
# add a status bar to the main window
status_bar = QtGui.QStatusBar()
status_bar.showMessage('Status bar')
self.main_window.setStatusBar(status_bar)
if __name__ == '__main__':
app = App(sys.argv)
sys.exit(app.exec_())
Hola Mundo
Este código básico abrirá una ventana GUI “Hola mundo” usando PyQt4:
import sys
from PyQt4 import QtGui
# create instance of QApplication
app = QtGui.QApplication(sys.argv)
# create QLabel, without parent it will be shown as window
label = QtGui.QLabel('Hello world!')
label.show()
# start the execution loop of the application
sys.exit(app.exec_())
Este es el mismo código que usa PyQt5.
import sys
from PyQt5 import QtWidgets
# create instance of QApplication
app = QtWidgets.QApplication(sys.argv)
# create QLabel, without parent it will be shown as window
label = QtWidgets.QLabel('Hello world!')
label.show()
# start the execution loop of the application
sys.exit(app.exec_())
Una muestra simple de arrastrar y soltar
Cree una aplicación GUI simple en 3 sencillos pasos.
1. Diseño
Abra Qt Creator
, cree un nuevo proyecto y haga su diseño. Guarde su resultado como archivo .ui
(aquí: mainwindow.ui
).
2. Generar el archivo .py correspondiente
Ahora puede crear un archivo .py a partir de su archivo .ui que generó en el paso anterior. Ingrese lo siguiente en su línea de comando:
$ pyuic4 mainwindow.ui -o GUI.py
Si la línea anterior se ejecuta correctamente, se crea un archivo GUI.py
.
3. Códigos de Python
Puede agregar su propio código (por ejemplo, señales y ranuras) en el archivo GUI.py
pero es mejor agregarlos en un archivo nuevo. Si alguna vez desea realizar cambios en su GUI, se sobrescribirá el archivo GUI.py
. Es por eso que usar otro archivo para agregar funcionalidad es mejor en la mayoría de los casos.
Llamemos al nuevo archivo main.py
.
from PyQt4 import QtGui
import sys
import GUI # Your generated .py file
class MyApp(QtGui.QMainWindow, GUI.Ui_MainWindow):
def __init__(self, parent=None):
super(ExampleApp, self).__init__(parent)
self.setupUi(self)
# Connect a button to a function
self.btn_run.clicked.connect(self.run)
def run(self):
# Write here what happens after the button press
print("run")
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()
Ahora puede ejecutar main.py
y ver su GUI.
Instalación de PyQt4
Método de instalación sugerido
Windows: Descargue y ejecute el archivo de configuración binario.
Linux(Debian): Ejecute este comando en su línea de comandos:
$ apt-get install python-qt4 pyqt4-dev-tools qt4-designer
OS X: Ejecute este comando en su línea de comando:
$ brew install pyqt
Instale manualmente
También puede descargar el código fuente manualmente desde aquí y luego instalarlo y configurarlo usted mismo.
Prueba tu instalación
Si pyqt está instalado correctamente, podrá ejecutar el comando pyuic4
. Si está instalado correctamente, verá el siguiente error:
$ pyuic4
Error: one input ui-file must be specified
Instalación completa
Ahora ha instalado la biblioteca PyQt4. También se han instalado dos aplicaciones útiles junto con PyQt4:
- Qt Designer: Una aplicación para el diseño ‘drag & drop’ de interfaces gráficas (crea archivos
.ui
), - pyuic4: una aplicación de línea de comandos que puede convertir archivos
.ui
en código Python.