Ejemplo Wxwidgtes
Ejemplo Wxwidgtes
Ejemplo Wxwidgtes
LECCIÓN 1
http://zetcode.com/gui/wxwidgets/
Clases De Wxwigets
https://www.youtube.com/playlist?list=PLClKgnzRFYe5XG7x7Gacz29-Cjjr_jzZT
https://docs.wxwidgets.org/trunk/overview_helloworld.html
Si bien no hace nada muy útil, presenta un par de conceptos importantes y explica
cómo escribir una aplicación wxWidgets que funcione.
Prácticamente todas las aplicaciones deberían definir una nueva clase derivada
de wxApp . Por imperiosas wxApp método virtual 's OnInit () el programa puede
ser inicializado, por ejemplo mediante la creación de una nueva ventana principal.
public:
};
public:
MyFrame();
private:
3
};
enum
{
ID_Hello = 1
};
Observe que no necesita definir identificadores para "Acerca de" y "Salir", ya que
wxWidgets ya predefine valores estándar como wxID_ABOUT y
wxID_EXIT. Debes utilizarlos siempre que sea posible, ya que pueden ser
manejados de manera especial por una plataforma en particular.
Como en todos los programas, debe haber una función "principal". En wxWidgets,
main se implementa dentro de la macro wxIMPLEMENT_APP () , que crea una
instancia de aplicación de la clase especificada y comienza a ejecutar el bucle de
eventos de la GUI( interfaz gráfica de usuario). Se usa simplemente como:
wxIMPLEMENT_APP (MyApp);
MyFrame :: MyFrame ()
: wxFrame (NULL, wxID_ANY , "Hola mundo" )
{
wxMenu * menuFile = new wxMenu ;
menuFile-> Append (ID_Hello, "& Hello ... \ tCtrl-H" ,
"Cadena de ayuda mostrada en la barra de estado para este elemento
de menú" );
menuFile-> AppendSeparator ();
menuFile-> Append (wxID_EXIT);
wxMenu * menuHelp = new wxMenu ;
menuHelp-> Append ( wxID_ABOUT );
wxMenuBar * menuBar = new wxMenuBar ;
menuBar-> Append (menuFile, "& File" );
menuBar-> Append (menuHelp, "& Help" );
SetMenuBar (menuBar);
CreateStatusBar ();
SetStatusText ( "¡Bienvenido a wxWidgets!" );
... continúa a continuación ...
Tenga en cuenta que no es necesario especificar las etiquetas para los elementos
de menú estándar wxID_ABOUTy wxID_EXITse les darán etiquetas estándar
(incluso traducidas correctamente) y aceleradores estándar correctos para la
plataforma actual, lo que hará que el comportamiento de nuestro programa sea
más nativo. Por este motivo, debería preferir reutilizar los ID estándar
(consulte Artículos en stock ) siempre que sea posible.
}
Nota
En los programas C ++ 11, puede ser conveniente utilizar lambdas sin
nombre en lugar de funciones para los controladores de eventos,
especialmente cuando se manejan eventos desde los controles, ya que
esto permite mantener el código que crea el control y maneja su evento
juntos en el mismo lugar. Aquí, por ejemplo, podríamos reemplazar el
controlador wxID_EXIT con solo
Enlazar ( wxEVT_MENU , [=] ( wxCommandEvent &) {Cerrar ( verdadero
);}, wxID_EXIT );
7
http://wiki.codeblocks.org/index.php/WxSmith_tutorial:_Hello_
world
Windows users should see the wiki page:Compiling wxWidgets 2.8.6 to develop
Code::Blocks (MSW) or Installing Code::Blocks from source on
Windows or WxWindowsQuickRef. There are two ways to install the wxWidgets libraries,
You can download the wxWidgets source and compile it yourself, or you can download the
wxPack from [1] and install it. The wxPack contains a pre-compiled wxWidgets library, so
you can save a lot of time by that route.
Ubuntu Linux users can install wxWidgets from the Ubuntu repositories. Be sure to
install also build-essential to get the C++ compiler.
We will assume that you have wxWidgets ready and working with Code::Blocks. You should
probably create a directory with a name something like CBProjects for saving your work on
these tutorials. Each tutorial will be a separate "project" and will occupy a file in this directory.
After downloading and installing Code::Blocks, double-click its icon on the desktop to start it.
Here is the Code::Blocks opening window:
8
Click "Create a New Project" and then find and double-click the wxWidgets Project icon,
pointed to by the cursor in the screenshot below.
9
The next screen is a "Welcome" screen. Unless you just enjoy being welcomed by the
program, you will check the box which eliminates it on future startups.
The next screen looks like this:
10
Select wxWidgets 2.8x and click the "Next >" button at the bottom of the screen.
That brings you to the window where you specify the Project title and folder where you want to
save the project. Other fields are then filled automatically. I chose “Plain” as the Project title
and the other fields then adjusted to look like this:
Then click the “Next >” button at the bottom. The next screen, shown below, allows you to
mark your work with your identity. Fill in what you wish.
11
That brings up the window for choosing the GUI builder you want to use, wxSmith or
FormBuilder. We choose, of course, wxSmith.
12
The final screen of this sort asks whether we want to use the standard, default, configuration or
to use Advanced options. We will take the default. But, at the bottom, we choose to “Create
and use precompiled headers" which speeds up compilations after the first.
14
In wxWidgets 3.0.2 the screen looks like this. WardXmodem 21:38, 20 May 2015 (CEST)
15
On the form where we chose the directory for saving the project, we chose a real directory, but
that choice may lead to problems when you want to compile your project on other computers.
Another choice is to use the Global Variable system. To open the dialog below or modify or
change this global variable, you should click on the Code::Blocks main menu item Settings |
Global variables. That brings up the Global Variables Editor.
When you use it, the location of the wxWidgets library is read from the variable you supply.
This means that the location of the wxWidgets directory is not hard-coded inside your project,
but is stored inside the global configuration of Code::Blocks. When your project is opened on a
different computer, it will use that comoputer's configuration. The easiest option to use this
global variable is to leave $(#wx) which means to use the global variable named wx. This name
is reserved for wxWidgets and should be chosen in most cases.
When you use the global variable for the first time, it will ask for the wxWidgets directory. The
only thing you need to do here is to enter a valid location in base field. This is required only for
the first time since Code::Blocks will automatically use this setting for other projects you create.
In the middle of the right side of the window, under the word “Plainframe.wxs”, is a panel with
two square icons on the left; the one on the left brings up the menu bar editor while the one on
the right brings up the status bar editor. We will return to the menu bar editor in the next
tutorial. Below this panel and looking like a field of dots is the Editor window, where we will see
both the GUI forms which we build and the C++ code we write. In the lower left corner of the
whole window is the Properties/Events window, which will allow us to set properties of the
component we are working on or to pick events, such as “OnClick” , to which we need to
respond. To show properties, click on the left icon; to show events, click on the right icon
marked {} to suggest C++ code.
Above the Properties/Events window is the Management window with three tabs, Projects,
Symbols, and Resources. If all three tabs are not visible, drag the right border of the window to
17
the right to reveal all three. (A “resource” in wxSmith parlance usually means a “form” or
"window".) Above the Management window is a panel with several small but useful icons (
) to
Add the call to the Close() function so that the spot looks like this:
Hello, World!
We now turn to the classic first program, namely getting the words “Hello, World!” onto the
screen. The text could be added directly into the frame, as in GUI designers for a single
operating sytem; but we need to learn to use sizers for cross-platform programming. What are
sizers?
If you have been working with Java or Qt, you may remember something called Layout
managers. The implementation in wxWidgets differs a little but does almost the same thing.
19
When adding components into windows you must somehow specify their position and size.
wxWidgets tries to automate this process, and it uses sizers to do so. They automatically
position and size window components, and they can also set the size of the window so that
everything fits inside.
Sizers have one big advantage over direct placement of components. When you write cross-
platform applications, you cannot assume that fonts, buttons, and so on have the same size on
different operating systems. This problem can even occur on the same platform when using
different window themes. When you use sizers, you don't have to worry about those problems.
All sizing and placement is done automatically. Moreover, sizers can even reposition and
resize window components when the main window changes size.
With that background, let's get started. When you look at the wxSmith editor, you'll notice that
the area of the window is surrounded by eight black boxes or drag handles.
These drag handles surround the currently selected item. In our case it's a whole window.
Adding new components to the window is simply done by clicking on one of the buttons in the
palette at the bottom of the editor and then clicking somewhere on the resource. As you can
see here,
when you keep your mouse cursor over a component in the palette, it will show its name. That
feature may help you find components until you become familiar with their icons.
Let's add a new wxPanel component to our window; it is the fourth icon from the left on the
standard tab. You will see that when you click the wxPanel item and then move the cursor over
the editor, some part of the editor will change color. That's intentional and is used to show
where on the window the new item will be added.
After the wxPanel is in place, you will notice that the background color of the window has
changed to light gray. Now our window will look much more like other windows. Note that
currently the selection changed to the added panel but since its size is equal to the frame's, it's
hard to find out what's really selected. To make sure that wxPanel is selected, click somewhere
on the light gray area of our window (Note to Linux users: wxFrame and wxPanel usually have
the same background so it may look like nothing has changed; you may ensure that there's a
wxPanel by looking into the resource browser).
If you want to see the selection exactly or select items that overlap, you can use the resource
browser. To show it, click on the resources tab located in the same place where the project
browser is:
20
The resource tab consists of two parts. The first is the resource tree which shows the structure
of your resources and the second one is the property browser which is common in GUI
designers. Inside the resource tree you can find the currently selected item. In our case it is the
wxPanel class we added before. The selected item also shows the name of this item: Panel1.
This name is basically the variable which can be used to access this component in your code.
We added a new component by selecting the place for it. This is wxSmith's default behavior.
However, there is another mode of adding items. In this mode, the new item is added right
after you click on the palette's button. The position of the new item is relative to the current
selection - just like a cursor in text editors. Basically we can add new items into three different
positions relative to the selection:
The uppermost is the mode we used - "point by mouse". The next one means "add into",
followed by "add before", and the last one means "add after". The current mode is shown by a
red check mark on the button.
Sometimes a few selection modes are disabled because they are not valid for the currently
selected item. For example, you cannot add any component into the wxButton component
since wxWidgets declares it as one that cannot have child components. Similarly, when the
main component (the window) is selected, you won't be able to add anything after it or before
it.
Ooops! I said we would use sizers and then forgot all about them! We have to get rid of that
wxPanel. Select the panel and then click on the red X button just below the four buttons we
have been describing. It looks like this:
When you click this button, it deletes the current selection, so if the panel didn't disappear,
make sure it's selected and click the button again. Now we should have returned to the state at
the beginning.
To use sizers, first we have to add a sizer into the main frame and then add the wxPanel into it.
Sizers are available in the Layout tab on the palette. Switch to it and select wxBoxSizer:
This sizer tries to position items in one line, either horizontal or vertical. Horizontal is the
default, and we will use it.
After adding the sizer, two things have changed. The first is that our window now has a red
border. This means that there is a sizer attached to it. When you look into the resource
browser, you will also see that the sizer has been added. (You may need to click on the editor
area to refresh the selection on the resource browser.) The second change is that the size of
the window has shrunk to a small box. That is as it should be because the sizer is responsible
for resizing the window to be no bigger than necessary to be visible and accommodate its
components, and so far there are no components.
Now let's add our wxPanel. Make sure that you add it into the sizer, not into the main frame.
After you do so, you will see something like this:
22
Here we can see our panel surrounded by drag boxes. There's also some dark gray border
around it (it won't be visible on Linux). Each component added into the sizer can be
surrounded by such a border. It's useful when you want to have spacing between components.
But in our case we should get rid of it to get a better looking window. To do so, we will have to
change a property inside the property browser. Search for border size and change it from 5 to
0:
Now when we have our panel adjusted, we can finally add the "Hello world" text. Since we will
also use sizers to manage items added into wxPanel, we have to repeat the addition of
wxBoxSizer into wxPanel. After the sizer is in its place, switch back into the Standard tab on
the palette and add a wxStaticText control:
With an eye to the future and for practice with adding components, let's add also a button next
to the wxStaticText. First, click on wxButton. If you still have the "point by mouse" insertion
mode turned on, then when you put the mouse over the wxStaticText component half of that
component will be colored in light blue. When the left half of the text is highlighted, the new
item will be added before the existing component; and when the right half is highlighted, the
new component will be added after the existing one. Let's add the button after the text. Now we
should have this content:
23
Now let's finally set our "Hello, World!" text. The wxStaticText control which we added before
has the text "Label" on it. It is the default text set to all newly created wxStaticText classes. We
will change it using the property browser similarly to changing the border size in the wxPanel
class. To do so, select the wxStaticText component in our window, then find the Label property
in the property browser and change it to "Hello, World!":
If you want two or more lines of text on the wxStaticText control. click on the "..." button at the
right end of the “Label” line or put "\n" inside the text, as in C formats.
At this point, you can click the "Build and run" and the program should run and show the magic
words in the static text control. We could quit in triumph at this point, but the button we have
put on the form is still a dud; clicking on it will do nothing. Let's give it a function.
Before going further, we need to deal with a question you may be asking. Why did we, after
putting a box sizer onto our main window, proceed to put a wxPanel into it and then put
another box sizer onto the panel? What is the point of the panel? Why not just put our two
buttons into the first box sizer and eliminate the panel and second box sizer? The answer is
that the panel gives us control of the background. We didn't use it, but it is often useful to be
able to control it. In fact, these first three steps will be used in structuring every window used in
these tutorials. To review, these three steps are:
Since buttons usually cause something to happen when clicked, let's make our button close
the window. The first thing we should do is to change the text shown on the button to tell the
user what the button does. It is done just as in the case of the wxStaticText widget. Select the
button, find "Label" in the property browser and set it to "Close" (or anything you like).
The second thing is to assign an event handler to this button. Basically, event handlers are
functions which are called when some "event" occurs. In our case instead of "event" we could
say more descriptively " a click on the button" because that is what we want to process. Like
other GUI designers, wxSmith can automatically generate the framework code for such
handlers. To bring up that ability, switch the property browser to the event browser by clicking
on the second icon at the top of the property browser. The icon looks like {} to suggest C++
code.
After you click on this icon, you will see all events supported by the currently selected
component. The wxButton class supports only one event, the EVT_BUTTON event, so only
this one is shown. When you click on this event and drop down the combo box, you will see the
available options and handlers for this event:
If you select -- None -- no handler function will be automatically assigned to this event. (But it
may always be set manually.) Selecting -- Add new handler -- will generate a frame for the
code of the new handler function. Below are shown other event handlers known to wxSmith
which can be assigned to this event. We can see here OnQuit and OnAbout. Those handlers
were created by wizard. We could use the OnQuit handler, but to see what happens, let's write
our own handler. Select the Add new handler option. You will be asked for a name for the
handler. This name is simply the name of the function which will be called as a reaction to this
event. wxSmith will suggest the name OnButton1Click, and we may as well use it.
When you enter a new handler name, wxSmith will generate the framing code of a new handler
function by that name, open the program file with the proper source code and put the cursor
inside the handler function. (You may need to scroll up or down to show the line with cursor.)
This function is a member of the class we have been building, so it can access all of functions
in that class, including the one called Close(), which was created by the wizard. So when we
want to close our window we just call the Close() function. The result looks like this:
25
Build and run our project. It should show our "Hello, World!" text and our "Close" button. Click
the Close button, and it should close.
This is end of this first tutorial, I hope that you followed it easily and are beginning to feel
comfortable with Code::Blocks and wxSmith.
The tutorial was originally written by BYO, the creator of wxSmith. It was revised in March 2012
by Grouch to take account of changes in Code::Blocks, add a few clarifications, and change
the accent in the English from youthful Polish to elderly American.
26
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
public:
};
public:
MyFrame();
private:
};
enum
{
ID_Hello = 1
};
wxIMPLEMENT_APP(MyApp);
bool MyApp::OnInit()
frame->Show(true);
return true;
MyFrame::MyFrame()
menuFile->Append(ID_Hello, "&Hello...\tCtrl-H",
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
menuHelp->Append(wxID_ABOUT);
28
menuBar->Append(menuFile, "&File");
menuBar->Append(menuHelp, "&Help");
SetMenuBar( menuBar );
CreateStatusBar();
SetStatusText("Welcome to wxWidgets!");
Close(true);
Los usuarios de Windows deberían ver la página wiki: Compilar wxWidgets 2.8.6 para
desarrollar Code :: Blocks (MSW) o Instalar Code :: Blocks desde la fuente en
Windows o WxWindowsQuickRef . Hay dos formas de instalar las bibliotecas wxWidgets.
Puede descargar el código fuente wxWidgets y compilarlo usted mismo, o puede
descargar el wxPack desde [1] e instalarlo. El wxPack contiene una biblioteca wxWidgets
precompilada, por lo que puede ahorrar mucho tiempo por esa ruta.
Los usuarios de Ubuntu Linux pueden instalar wxWidgets desde los repositorios de
Ubuntu. Asegúrese de instalar también build-essential para obtener el compilador de C +
+.
Asumiremos que tiene wxWidgets listos y funcionando con Code :: Blocks. Probablemente
debería crear un directorio con un nombre similar a CBProjects para guardar su trabajo en
estos tutoriales. Cada tutorial será un "proyecto" separado y ocupará un archivo en este
directorio.
Después de descargar e instalar Code :: Blocks, haga doble clic en su icono en el escritorio
para iniciarlo. Aquí está la ventana de apertura de Code :: Blocks:
30
Haga clic en "Crear un nuevo proyecto" y luego busque y haga doble clic en el icono del
proyecto wxWidgets, señalado por el cursor en la siguiente captura de pantalla.
31
Luego haga clic en el botón "Siguiente>" en la parte inferior. La siguiente pantalla, que se
muestra a continuación, le permite marcar su trabajo con su identidad. Complete lo que desee.
33
Eso abre la ventana para elegir el constructor de GUI que desea usar, wxSmith o
FormBuilder. Elegimos, por supuesto, wxSmith.
34
Cree el programa, o
Ejecutarlo, o
Constrúyalo y ejecútelo, o
39
Reconstruirlo o
Abortarlo.
Cuando pase el cursor sobre ellos, la información sobre herramientas le dirá cuál es cuál.
Ahora vuelve a mirar la ventana del Editor. En primer lugar, tenga en cuenta que la ventana se
puede configurar para utilizar diferentes colores, fuentes y tamaños de fuente. Haga clic en
"Configuración ..." en el menú principal de Code :: Blocks, y luego en "Editor". Las pantallas
son más o menos autoexplicativas.
Ahora volvamos a la ventana del Editor. En la parte superior verá tres puntos cuadrados
negros llamados controles de arrastre. Se han configurado para cubrir un espacio más grande
del que se puede ver, pero al desplazarse hacia abajo se revela todo el campo.
Como programador experimentado, sabes que tiene que haber algún código en alguna parte,
pero no lo ves. Para revelarlo, haga doble clic izquierdo en el campo de puntos. Presto, está el
código C ++ y la pestaña * PlainMain.cpp ha aparecido encima. Al volver a hacer clic en
Plainframe.wxs, debería regresar a la vista del formulario, que sigue siendo el campo de
puntos. (Nuevamente, es importante tener CB 10.04 o posterior). De hecho, todavía no hemos
visto todo el código. En particular, buscará en vano la importantísima rutina OnInit () que inicia
el programa. Sin embargo, puede encontrarlo haciendo clic en Buscar | Busque en Archivos y
busque OnInit con el alcance de la búsqueda establecida como “Archivos de proyecto”. La
búsqueda lo encuentra, efectivamente, en PlainApp.cpp y abre este módulo en la ventana del
Editor.
La siguiente discusión sobre tener que agregar close () ya no es cierta, al menos en
Code :: Blocks 13.12, wxWidgets 3.0.2.
No necesitamos OnInit en este momento, pero necesitamos hacer un cambio en
PlainMain.cpp o cualquier otro nombre que le halla asignado al proyecto. Haga clic en él en la
barra sobre el editor y su código aparecerá en el editor.
A veces, un programa tiene mucho que hacer cuando el usuario hace clic en el icono de cierre
en la barra de título del programa, por lo que wxSmith genera un marco para escribir el código
para esas acciones, pero no proporciona código. En consecuencia, si ejecutamos nuestro
programa tal como lo escribió inicialmente wxSmith, no podremos cerrarlo simplemente
haciendo clic en ese icono. Para solucionar ese inconveniente problema, busque el lugar en el
código con estas líneas:
Destroy ();
}
( Descubrí que tenía que ser Destroy () not Close () WardXmodem 04:43, 24 de septiembre
de 2013 (CEST) )
( Uso event.Skip (TRUE); en lugar de Close ();. O destruir () (Algunos) más tarde tutoriales
correctamente hacen referencia a esta. Engañador 03/08/2015 )
Recuerde realizar este cambio inmediatamente cada vez que inicie un nuevo proyecto.
Fin de la antigua sección "tengo que agregar close ()". Con las versiones más
recientes, se hace lo siguiente:
¡Hola Mundo!
Pasamos ahora al primer programa clásico, a saber, las palabras "¡Hola, mundo!" en la
pantalla. El texto se puede agregar directamente al marco, como en los diseñadores de GUI
para un solo sistema operativo; pero necesitamos aprender a usar medidores para la
programación multiplataforma. ¿Qué son los calibradores?
41
Si ha estado trabajando con Java o Qt, es posible que recuerde algo llamado administradores
de diseño. La implementación en wxWidgets difiere un poco pero hace casi lo mismo.
Al agregar componentes a las ventanas, debe especificar de alguna manera su posición y
tamaño. wxWidgets intenta automatizar este proceso y utiliza medidores para
hacerlo. Posicionan y dimensionan automáticamente los componentes de la ventana, y
también pueden establecer el tamaño de la ventana para que todo quepa dentro.
Los calibradores tienen una gran ventaja sobre la colocación directa de componentes. Cuando
escribe aplicaciones multiplataforma, no puede asumir que las fuentes, botones, etc. tienen el
mismo tamaño en diferentes sistemas operativos. Este problema puede ocurrir incluso en la
misma plataforma cuando se utilizan diferentes temas de ventana. Cuando usa medidores, no
tiene que preocuparse por esos problemas. Todo el dimensionamiento y la colocación se
realiza automáticamente. Además, los medidores pueden incluso reposicionar y cambiar el
tamaño de los componentes de la ventana cuando la ventana principal cambia de tamaño.
Con ese trasfondo, comencemos. Cuando mires el editor de wxSmith, notarás que el área de
la ventana está rodeada por ocho cuadros negros o controles de arrastre.
generalmente tienen el mismo fondo, por lo que puede parecer que nada ha cambiado; puede
asegurarse de que haya un wxPanel mirando en el navegador de recursos).
Si desea ver la selección exactamente o seleccionar elementos que se superponen, puede
utilizar el navegador de recursos. Para mostrarlo, haga clic en la pestaña de recursos ubicada
en el mismo lugar donde está el navegador del proyecto:
La pestaña de recursos consta de dos partes. El primero es el árbol de recursos que muestra
la estructura de sus recursos y el segundo es el navegador de propiedades que es común en
los diseñadores de GUI. Dentro del árbol de recursos puede encontrar el elemento
seleccionado actualmente. En nuestro caso, es la clase wxPanel que agregamos antes. El
elemento seleccionado también muestra el nombre de este elemento: Panel1. Este nombre es
básicamente la variable que se puede utilizar para acceder a este componente en su código.
Agregamos un nuevo componente seleccionando el lugar para él. Este es el comportamiento
predeterminado de wxSmith. Sin embargo, hay otro modo de agregar elementos. En este
modo, el nuevo elemento se agrega justo después de hacer clic en el botón de la paleta. La
posición del nuevo elemento es relativa a la selección actual, como un cursor en los editores
de texto. Básicamente, podemos agregar nuevos elementos en tres posiciones diferentes en
relación con la selección:
Este modo de inserción se puede cambiar haciendo clic en uno de los cuatro botones de
"ubicación" en el lado derecho del editor:
El más alto es el modo que usamos - "señalar con el mouse". El siguiente significa "agregar
a", seguido de "agregar antes", y el último significa "agregar después". El modo actual se
muestra con una marca de verificación roja en el botón.
A veces, algunos modos de selección están deshabilitados porque no son válidos para el
elemento seleccionado actualmente. Por ejemplo, no puede agregar ningún componente al
componente wxButton ya que wxWidgets lo declara como uno que no puede tener
componentes secundarios. Del mismo modo, cuando se selecciona el componente principal
(la ventana), no podrá agregar nada después o antes.
¡Vaya! ¡Dije que usaríamos medidores y luego me olvidé de ellos! Tenemos que deshacernos
de ese wxPanel. Seleccione el panel y luego haga clic en el botón X rojo justo debajo de los
cuatro botones que hemos estado describiendo. Se parece a esto:
Cuando hace clic en este botón, elimina la selección actual, por lo que si el panel no
desapareció, asegúrese de que esté seleccionado y vuelva a hacer clic en el botón. Ahora
deberíamos haber regresado al estado al principio.
Para usar medidores, primero tenemos que agregar un medidor en el marco principal y luego
agregar el wxPanel en él. Los medidores están disponibles en la pestaña Diseño de la
paleta. Cambie a él y seleccione wxBoxSizer:
Este medidor intenta colocar los elementos en una línea, ya sea horizontal o
vertical. Horizontal es el valor predeterminado y lo usaremos.
Después de agregar el medidor, dos cosas han cambiado. La primera es que nuestra ventana
ahora tiene un borde rojo. Esto significa que tiene un medidor adjunto. Cuando mire en el
navegador de recursos, también verá que se ha agregado el medidor. (Es posible que deba
hacer clic en el área del editor para actualizar la selección en el navegador de recursos). El
segundo cambio es que el tamaño de la ventana se ha reducido a un cuadro pequeño. Así
debe ser porque el medidor es responsable de cambiar el tamaño de la ventana para que no
44
sea más grande de lo necesario para ser visible y acomodar sus componentes, y hasta ahora
no hay componentes.
Ahora agreguemos nuestro wxPanel. Asegúrese de agregarlo al medidor, no al marco
principal. Después de hacerlo, verá algo como esto:
Aquí podemos ver nuestro panel rodeado de cuadros de arrastre. También hay un borde gris
oscuro a su alrededor (no será visible en Linux). Cada componente agregado al medidor
puede estar rodeado por dicho borde. Es útil cuando desea tener espacio entre los
componentes. Pero en nuestro caso deberíamos deshacernos de él para tener una ventana
más atractiva. Para hacerlo, tendremos que cambiar una propiedad dentro del navegador de
propiedades. Busque el tamaño del borde y cámbielo de 5 a 0:
Ahora, cuando tengamos nuestro panel ajustado, finalmente podemos agregar el texto "Hola
mundo". Dado que también usaremos medidores para administrar los elementos agregados a
wxPanel, tenemos que repetir la adición de wxBoxSizer a wxPanel. Una vez que el medidor
esté en su lugar, vuelva a la pestaña Estándar en la paleta y agregue un control wxStaticText:
Con miras al futuro y para practicar la adición de componentes, agreguemos también un botón
al lado de wxStaticText. Primero, haga clic en wxButton. Si todavía tiene activado el modo de
inserción "señalar con el mouse", cuando coloque el mouse sobre el componente
45
Si desea dos o más líneas de texto en el control wxStaticText. haga clic en el botón "..." en el
extremo derecho de la línea "Etiqueta" o coloque "\ n" dentro del texto, como en los formatos
C.
En este punto, puede hacer clic en "Construir y ejecutar" y el programa debería ejecutarse y
mostrar las palabras mágicas en el control de texto estático. Podríamos salir triunfantes en
este punto, pero el botón que hemos puesto en el formulario sigue siendo un fracaso; hacer
clic en él no hará nada. Démosle una función.
Antes de continuar, debemos abordar una pregunta que pueda estar haciendo. ¿Por qué,
después de colocar un medidor de cajas en nuestra ventana principal, procedimos a colocar
un wxPanel y luego pusimos otro medidor de cajas en el panel? ¿Cuál es el punto del
panel? ¿Por qué no poner nuestros dos botones en el primer medidor de caja y eliminar el
panel y el segundo medidor de caja? La respuesta es que el panel nos da el control del
fondo. No lo usamos, pero a menudo es útil poder controlarlo. De hecho, estos tres primeros
pasos se utilizarán para estructurar todas las ventanas utilizadas en estos tutoriales. Para
revisar, estos tres pasos son:
46
Después de hacer clic en este icono, verá todos los eventos admitidos por el componente
seleccionado actualmente. La clase wxButton admite solo un evento, el evento EVT_BUTTON,
por lo que solo se muestra este. Al hacer clic en este evento y desplegar el cuadro combinado,
verá las opciones y controladores disponibles para este evento:
función es un miembro de la clase que hemos estado construyendo, por lo que puede acceder
a todas las funciones de esa clase, incluida la llamada Close () , que fue creado por el
asistente. Entonces, cuando queremos cerrar nuestra ventana, simplemente llamamos a la
función Close () . El resultado se ve así:
Este es el final de este primer tutorial, espero que lo haya seguido fácilmente y comience a
sentirse cómodo con Code :: Blocks y wxSmith.
El tutorial fue escrito originalmente por BYO, el creador de wxSmith. Fue revisado en marzo de
2012 por Grouch para tener en cuenta los cambios en Code :: Blocks, agregar algunas
aclaraciones y cambiar el acento en el inglés del polaco juvenil al estadounidense mayor.
Índice | próximo