elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Guía rápida para descarga de herramientas gratuitas de seguridad y desinfección


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  [Tutorial]Aprendiendo PyQT4 [Parte4]- JaAViEr (0x5d)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Tutorial]Aprendiendo PyQT4 [Parte4]- JaAViEr (0x5d)  (Leído 1,682 veces)
0x5d

Desconectado Desconectado

Mensajes: 241



Ver Perfil WWW
[Tutorial]Aprendiendo PyQT4 [Parte4]- JaAViEr (0x5d)
« en: 13 Febrero 2012, 02:27 am »

Hola nuevamente !

 En la [Parte3] dejé pendiente hablar sobre como obtener los datos de un QLineEdit(), voy a ir directo al grano :P.

 Pondré un ejemplo sencillo, tenemos el QLineEdit():
Código
  1. self.input_datos = QtGui.QLineEdit(self)
Entonces para obtener lo que ingresamos, usamos la propiedad .text() acompañada de un str() para que no devuelva el objeto y si el valor:
Código
  1. variable = str(self.input_datos.text())

  Entonces solo bastaría poner dicha línea en la función del botón(self.connect):
Código
  1. def funcion(self):
  2.  recibo_datos = str(self.input_datos.text())
  3.  
Y con ello ya tendremos en nuestras manos el valor del QLineEdit() en la variable. Ahora con ella podemos hacer lo mismo que hacemos en nuestros códigos Python normales, a nuestro antojo.

 Pero como quedó pendiente en la pasada parte sobre utilizar el valor del QLineEdit() en el QLabel(), con lo que hemos visto ya deberíamos saber hacerlo :D, de todas formas dejaré el código con comentarios :
Código
  1. # -*- coding: utf-8 -*-
  2. from PyQt4 import QtCore, QtGui
  3. import sys
  4.  
  5. class Mi_Programa(QtGui.QWidget):
  6.  
  7.  def __init__(self, parent=None):
  8.  
  9.    QtGui.QWidget.__init__(self, parent)
  10.    self.resize(200,134)
  11.    #Creamos los Labels,label_mensaje "Mensaje:", label_resultado el mensaje de "Resultado:"
  12.    #Y el tercero mostrará el texto ingresado.
  13.    self.label_mensaje = QtGui.QLabel("Mensaje:", self)
  14.    self.label_mensaje.setGeometry(3,14,59,17)
  15.    self.label_resultado = QtGui.QLabel("Resultado:", self)
  16.    self.label_resultado.setGeometry(5,80,71,17)
  17.    self.label_show = QtGui.QLabel("",self)
  18.    self.label_show.setGeometry(80,80,111,17)
  19.    #Creamos el QLineEdit para pedir datos
  20.    self.input_datos = QtGui.QLineEdit(self)
  21.    self.input_datos.setGeometry(60,10,113,27)
  22.    #Creamos el Boton
  23.    self.mi_boton = QtGui.QPushButton("Dame Clic", self)
  24.    self.mi_boton.setGeometry(60,40,92,27)
  25.    #Le damos función al botón
  26.    self.connect(self.mi_boton, QtCore.SIGNAL('clicked()'), self.show_message)
  27.  
  28.  def show_message(self):
  29.    mensaje = str(self.input_datos.text())
  30.    self.label_show.setText(mensaje)
  31. aplicacion = QtGui.QApplication(sys.argv)
  32. formulario = Mi_Programa()
  33. formulario.show()
  34. aplicacion.exec_()
  35.  
Explico un poco:
Al dar clic en el botón, llamamos a la función show_message() en la cual obtendremos el dato de self.input_datos, posteriormente guardamos el valor en la variable mensaje y como ya vimos, usamos setText(mensaje) para darle el nuevo valor al QLabel().

  Supongo que ya no hay temas pendientes con QLineEdit, QLabel, QPushButton :P, veamos el uso de otros Widgets, el siguiente es QPlainTextEdit().

  Como dice su nombre, es para insertar un texto plano, a diferencia del QLineEdit, este es multilíneas.

 La manera de utilización es la siguiente :
Código
  1. self.texto_plano = QtGui.QPlainTextEdit("", self)
Como ya sabemos, usamos la propiedad setGeometry() para dar posición, ancho y altura.
 
  Para obtener los datos que se insertan en dicho widget, usaremos la propiedad toPlainText(), que es el equivalente al .text() del QLineEdit.

  Para insertar datos en un QPlainTextEdit(), debemos usar setPlainText('Msj').

Un pequeño ejemplo de lo que he escrito en código :
Código
  1. # -*- coding: utf-8 -*-
  2. from PyQt4 import QtCore, QtGui
  3. import sys
  4.  
  5. class Mi_Programa(QtGui.QWidget):
  6.  
  7.  def __init__(self, parent=None):
  8.  
  9.    QtGui.QWidget.__init__(self, parent)
  10.    self.resize(400,319) # Tamaño
  11.    #Creamos el primer PlainTextEdit que luego envía los datos al segundo
  12.    self.texto_plano = QtGui.QPlainTextEdit("", self)
  13.    self.texto_plano.setGeometry(10,10,191,271)
  14.    #Creamos el botón
  15.    self.transcribir = QtGui.QPushButton("Transcribir", self)
  16.    self.transcribir.setGeometry(10,285,95,27)
  17.    #Creamos el segundo PlainTextEdit que recibirá el primer contenido
  18.    self.nuevo_txt = QtGui.QPlainTextEdit("", self)
  19.    self.nuevo_txt.setGeometry(206,10,191,271)
  20.    #Le damos la función al botón y llamamos al def transcribe
  21.    self.connect(self.transcribir, QtCore.SIGNAL('clicked()'), self.transcribe)
  22.  
  23.  def transcribe(self):
  24.    #Obtenemos el contenido del primer QPlainTextEdit
  25.    contenido = self.texto_plano.toPlainText()
  26.    #Escribimos el contenido del primer QPlainTextEdit en el segundo
  27.    #Usando setPlainText
  28.    self.nuevo_txt.setPlainText(contenido)
  29.  
  30. aplicacion = QtGui.QApplication(sys.argv)
  31. formulario = Mi_Programa()
  32. formulario.show()
  33. aplicacion.exec_()


 Luego seguiré con el QTextBrowser(), que nos permite ingresar código HTML en el campo de escritura...

Fuente : http://rootcodes.com/tutorialaprendiendo-pyqt4-con-rootcodes-parte4/

Saludos, Javier.


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
[Código-PyQT4]All in one - JaAViEr(0x5d)
Scripting
0x5d 0 2,003 Último mensaje 11 Febrero 2012, 05:11 am
por 0x5d
[Tutorial]Aprendiendo PyQT4 [Parte1]- JaAViEr (0x5d)
Scripting
0x5d 0 2,158 Último mensaje 11 Febrero 2012, 20:00 pm
por 0x5d
[Tutorial]Aprendiendo PyQT4 [Parte2]- JaAViEr (0x5d)
Scripting
0x5d 0 1,446 Último mensaje 11 Febrero 2012, 20:13 pm
por 0x5d
[Tutorial]Aprendiendo PyQT4 [Parte3]- JaAViEr (0x5d)
Scripting
0x5d 0 1,576 Último mensaje 11 Febrero 2012, 20:21 pm
por 0x5d
[Python]Problema con QPushButton (PyQt4)
Scripting
[u]nsigned 0 1,998 Último mensaje 5 Junio 2012, 21:24 pm
por [u]nsigned
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines