miércoles, 25 de julio de 2012

Gtk + Textview y variables de clase

En este ejemplo también vamos a ver como podemos inicializar ciertas variables de una clase y las podrémos usar por toda la clase. Ejemplo: texto1, rojo, blanco,contador. Estas variables las declararemos antes del init de la clase.

Como vemos mucho del texto no es sintaxis propia de vala sino la de GTK+. Por lo tanto para alguien experimentado en Python Gtk (pygtk) o quien haya programado en este interface antes en uno u otro idioma la dinámica es parecida.

Este ejemplo es un pequeño programa en el cual cuando pulsamos el botón el texto se va descubriendo hacia la derecha.   Lo conseguimos usando un contador de posición y creando "tags" que son estilos de texto:(subrayado, negrita,fuente, color...)
e insertando esos estilos en ciertos "Iters" que son por así decirlo punteros para el texto del buffer.


[indent=4]
uses
    Gtk
init

    Gtk.init (ref args)
    var test = new TestWindow ()
    test.show_all ()
    Gtk.main ();
   
   
class TestWindow : Window
    texto1: Gtk.TextView = new TextView
   
    rojo: Gtk.TextTag
    blanco: Gtk.TextTag
    ti1: Gtk.TextIter
    ti2: Gtk.TextIter
    ti3: Gtk.TextIter
    ti4: Gtk.TextIter
       
    acolor : Gdk.Color
    cont:int=0
    boton1: Button= new Button.with_label ("Pulsa este botón")
    contador: int = 0
    palabras: new array of string
    frase:string ="La casa esta rota, pero ya la estamos arreglando"
    vbox : VBox = new VBox (true, 5)
       
    init
        Gdk.Color.parse("#1F2AF1", out acolor)
        rojo=texto1.buffer.create_tag("rojo", "foreground-gdk", acolor);
        blanco=texto1.buffer.create_tag("blanco", "foreground", "White");
       
        texto1.editable = false
        texto1.cursor_visible = false
        palabras= frase.split(" ")
        title = "Ventana de prueba"
        default_height = 360
        default_width = 560
        window_position = WindowPosition.CENTER
        boton1.clicked.connect (pulsado)
       
        destroy.connect(Gtk.main_quit)
        vbox.add (boton1)
        vbox.add(texto1)
        add (vbox)
        texto1.set_size_request(100, 200)
        texto1.buffer.text = frase
        texto1.buffer.get_iter_at_mark (out ti1, texto1.buffer.get_insert ())
        texto1.buffer.get_iter_at_mark (out ti2, texto1.buffer.get_insert ())
        texto1.buffer.get_iter_at_mark (out ti3, texto1.buffer.get_insert ())
        texto1.buffer.get_iter_at_mark (out ti4, texto1.buffer.get_insert ())
       
    def pulsado (btn : Button)
               
        contador++
        ti1.set_offset(0)
        ti2.set_offset(contador)
        ti3.set_offset(contador+5)
        ti4.set_offset(longitud(frase))
       
        texto1.buffer.remove_all_tags (ti1,ti4)
        texto1.buffer.apply_tag (blanco,ti1,ti2)
        texto1.buffer.apply_tag (rojo,ti2,ti3)
        texto1.buffer.apply_tag (blanco,ti3,ti4)


No hay comentarios:

Publicar un comentario