WXWindows 2
Write cross-platform programs with C
Chinese version
This tutorial is translated by GXL117 and will continue to maintain. This is the first draft of this tutorial. If you find an error, please contact me (email: gxl117@yahoo.com.cn) Let me fix it in time. After that, this tutorial will be more expanded, and the majority of netizens will be welcome to give advice.
This tutorial is published in the GPL protocol.
This license authorizes you to make and publish a copy of this tutorial, but keep this copyright declaration and license statement on all copies.
If you are ready to publish this document, please let the translator to make sure you get the latest version of this document.
The scope of application of this document is not guaranteed, it is only provided as a free resource. Therefore, the author and the maintainer of the information provided herein cannot make this information, certainly correct guarantees.
Franky Braem
Copyright? 2001-2002 Franky Braem
You are allowed to copy and to print this book as long as you do not exploit the information commercially. The author of this book makes no warranty of any kind, expressed or implied, with regard to the programs or the documentation contained in this book .
table of Contents
1.
Introduction Introduction
Why use wxwindows?
WxWindows
History
Hello World
2. wxframe
usage of
Create a FRAME
Constructor constructor
Add a control Adding a control
Add menu Adding a menubar
Add status bar adding a statusbar
Processing processing menu events
3.
Event processing EVENT HANDLING
Introduction Introduction
How does it work How IT Works
Event's jump EVENT SKIPPING
Prohibited an event vetoing an Event
Blocked an event handle Plug an Event Handler
4.
General dialog Common Dialogs
WXFiledialog
Constructor Constructor
Method Methods
Example EXAMPLE
WXFileSelector
WXCOLOURDIALOG
Construction constructor
Method Methods
WxcolourData
Example EXAMPLE
WxgetCOLOURFROMUSER
WXFONTDIALOGOG
Constructor Constructor
Method Methods
WXFONTDATA
Example EXAMPLE
WXPrintDialog
Constructor Constructor
Method Methods
Example EXAMPLE
WXDIRDIALOG
Constructor Constructor
Method Methods
Example EXAMPLE
WXDIRSELECTOR
WXTEXTENTRYDIALOGOGOG
Constructor Constructor
Method Methods
Example EXAMPLE
WxgetTextFromuser
WxGetPasswordFromuser
WxMessageDialog
Constructor Constructor
Method Methods
Example EXAMPLE
WxMessageBox
WXSinglechoiceDialog
Constructor Constructor
Method Methods
Example EXAMPLE
Wxgetsinglechoice
WxgetsinglechoiceIndex
WxgetsinglechoiceData
5.
Dialog box Dialogs
WxDialog
Constructor Constructor
Dialog Box Programming Dialogssizers
SIZERS AND Windows
SIZERS AND Other SIZERS
SIZERS AND SPACERS
WxBoxSizer
Wxgridsizer
WXFlexGridsizer
WxStaticBoxSizer
WxnoteBooksizer
Nesting sizers
List of flights
5.1. The About Dialog
5.2. The About Dialog Using A WXBOXSIZER
5.3. Using wxflexgridsizer
5.4. Nesting Sizers
List of tables
2. WXFrame Styles
4.1. Wxfiledialog styles
4.2. WxtextentryDialog Styles
4.3. WxMessageDialog Styles
4.4. WxsinglechoiceDialog Styles
5.1. Wxdialog styles
5.2. Wxsizer border flags
5.3. WXSIZER Behaviour Flags
5.4. Wxboxsizer orientation
List of example
1.1. A Resource File
1.2. A Makefile for MingW
1.3. Adding Additional Libraries to a makefile
1.4. HelloWorldapp.h - The HelloWorldApp Definition
1.5. HelloWorldapp.cpp - The Implementation of HelloWorldApp
1.6. Using the wxgetapp () Method
2.1. Step 1 - The textframe definition
2.2. Step 1 - The TextFrame IMPLEMENTATION
2.3. TextEditorapp.h - The TextEditorapp Definition
2.4. TextEditorapp.cpp - The TextEditorapp IMPLEMENTATION
2.5. Step 2 - The TextFrame Definition
2.6. Step 2 - The TextFrame IMPLEMENTATION
2.7. Step 3 - The textframe definition
2.8. Step 3 - The TextFrame IMPLEMENTATION
2.9. CREANG A STATUSBAR
2.10. Menus with a description Text
2.11. TextFrame.h - The Full Definition
2.12. TextFrame.cpp - The Full Implementation
3.1. An Event Table
3.2. NumTextCtrl.h - The NumTextCtrl Definition
3.3. NumTextCtrl.cpp - The NumTextCtrl Implementation
3.4. Vetoing an event
3.5. LOGEVENTHANDLER.H - The Definition of The Logeventhandler.
3.6. LOGEVENTHANDAL.CPP - The IMPLEMENTATION OF THE LOGEVENTHANDLER.
4.1. Using wxfiledialog
4.2. Using wxfileselector
4.3. Using wxcolourdialog
4.4. Using wxgetcolourfromuser4.5. Using wxfontdialog
4.6. Using wxdirdialog
4.7. Using WXDIRSELECTOR
4.8. Using wxtextentryDialog
4.9. Using wxgettextFromuser
4.10. Using WxGetPasswordFromuser
4.11. Using wxsinglechoicedialog
5.1. A Simple Resource File
5.2. Aboutdialog.h - The definition of the about-dialog
5.3. AboutDialog.cpp - The Implement of the About-Dialog
5.4. Showing a dialog
5.5. Using wxboxsizer
5.6. Using wxgridsizer
5.7. Using wxflexgridsizer
5.8. Nesting Sizers
Chapter 1. Introduction
Table of contents
Why use wxwindows?
WxWindows
History
Hello World
Why use wxwindows?
Do you want to use C to write on Windows, Linux or UNIX? This is almost impossible when each platform has their own Framework, appearance, behavior, or SDK. Of course, you will definitely don't want to write your procedures for every platform, which will be extremely difficult.
WXWindows is a solution. WxWindows hides all platform-related code. It is a Framework that is not related to the platform, it has the following characteristics:
It is very comprehensive and has a lot of practical classes. IT is Very Complete. There Are Many Utility Classes. It is still in fast development. IT is Still Heavily Developed. Support for many compilers and platforms: Windows, Linux, Mac, UNIX. Has a lot of documentation. The A Lot of Documentation. Individual and commercial organizations can use it freely. IT's Free for Personal and Commercial Uses. As long as WXWindows uses local SDK. This means that if a program is compiled under Windows, it will have the appearance and behavior of Linux programs when it compiles under Linux.
WXWindows history
Julian Smart has developed wxwindows in the Artificial Intelligent Project Academy of EDINBURGH University in 1992. In 1995, Markus Holzem completed the XT version of transplant. In 1997, Windows and GTK transplantation were integrated and put in the CVS archive.
Hello World
This first example is a well-known Hello World program. This program is a window that displays "Hello World" in the status bar.
Every wxwindow program has an object inherited from wxapp. Each program is instantiated with an onInit () method, you can create a main window here. Example 1.4 is the definition of HelloWorldApp:
Example 1.4. HelloWorldapp.h - The HelloWorldApp Definition
#ifndef INCLUDED_HELLOWORLDAPP_H #define INCLUDED_HELLOWORLDAPP_H / ** * HelloWorldApp Class * This class displays a status bar containing the text "Hello World" window * / class HelloWorldApp: public wxApp {public: virtual bool OnInit ();}; DECLARE_APP (HelloWorldApp) #ENDIF // INCLUDED_HELLOWORLDAPP_H For the main window we use the wxframe class. This class provides a window that adjusts the size and location. It has a thick border with a title bar. In addition, you can make it have a menu bar, toolbar, status bar. Example 1.5 is the implementation of HelloWorldApp.
Example 1.5. HelloWorldApp.cpp - HelloWorldApp's Implementation
/ / To support the pre-compilation compiler, "wx / wxprec.h" #include "wx / wxprec.h" #IFNDEF wx_precomp #include "wx / wx.h" #ENDIF #include "helloworldapp.h" implemement_app (HelloWorldApp) ) / * Program starts from here, similar to main () * / bool helloworldapp :: oninit () {wxframe * frame = new wxframe (wxframe *) NULL, -1, _T ("Hello World" )); frame-> createstatusbar (); frame-> setStatustext ("Hello World"); frame-> show (true); settopWindow;} Return True;}
When your compiler supports the pre-processor, you can use the wxprec header file. When it does not support, you should include wx.h, which contains all the necessary WXWindows header files. You can also include a corresponding header file for each control. (Translator Note: Under Linux uses wxframe constructor to use wxcha to perform explicit conversion, support for multi-byte characters can be solved using macro wxt (String)
Macro Declare_APP and IMPLEMENT_APP Take us: When the platform needs, it creates a main () or WinMain () method. It creates a global method wxgetApp (). You can use this function to get a reference to a program object:
Example 1.6. WxgetApp () Usage method HelloWorldApp & App = (HelloWorldApp &) WXGetApp ();
You may be strange why there is no code of the Frame variable anywhere in the program. Since the frame is set to the top window of the program, the program will automatically remove the frame when exiting.
Some bad compilers do not allow NULL implicit conversion to wxframe *, so why we want to make it, just out of steady consideration (but if you are really using such a compiler, I I suggest you still update it). At the same time, this is also more conducive to the transplantation of the program.
After Frame is created, use CreateStatusbar to create a status bar. The text content of the status bar is set to "Hello World". Call show () to display Frame. Show () is a way to inherit from wxwindow class. When OnNit returns false, the program will stop immediately. If something happens during the initialization of the program, you can use it to stop the program.
Chapter 2 uses wxframe directory
create
Constructor
Add a control
Add a menu bar
Add status bar
Handling menu event
The WXFrame class provides us a frame window. The frame window is a window that can change the size, it has a thick border with a title bar. In addition, you can make it have a menu bar, toolbar, status bar. The frame can be used as a window device for other controls, but does not contain another window or dialog. WXFrame is derived from the WXWindow class.
In this chapter we will create a small text editor.
Create a FRAME
Usually you can create your own class by inheriting wxframe. This allows you to add functions to your own Frame class. Example 2.1 is this, which is implemented in Example 2.2.
Example 2.1 - Define TextFrame
#ifndef _TEXTFRAME_H #define _TEXTFRAME_H class TextFrame: public wxFrame {public: / ** * constructor to create a new TextFrame * / TextFrame (const wxChar * title, int xpos, int ypos, int width, int height); /. ** * destructor * / ~ textFrame ();}; #ENDIF / / / _ TEXTFRAME_H
TextFrame constructor inherits the constructor from wxframe.
Example 2.2. TEXTFRAME implementation
/ / To support the preparatory compiler, "wx / wx.h" #include "wx / wxprec.h" #Ifndef wx_precomp #include "wx / wx.h" #ENDIF #include "textframe.h" textframe :: TEXTFRAME (Const WxChar * Title, INT XPOS, INT YPOS, INT WIDTH, INT Height): wxframe (wxframe *) NULL, -1, TITLE, WXPOINT (XPOS, YPOS), WXSIZE (Width, Height) {} textframe :: ~ textframe () {}
Constructor
wxFrame (wxWindow * parent, wxWindowId id, const wxString & title, const wxPoint & pos = wxDefaultPosition, const wxSize & size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE, const wxString & name = "frame");
Parent is a pointer to the parent window that uses NULL when the frame does not have a parent window. The ID is the only window identification number, when you don't need it, use -1. Title is the title of the frame, which will appear in the title bar of the frame. POS is the location of the frame. WxDefaultPosition represents the default value. SIZE is the size of the frame. WxDefaultsize represents the use of the default. Style is the style of the frame. Table 2.1. Wxfram style
WXDEFAULT_FRAME_STYLE WXMINIMIZE_BOX, WXMAXIMIZE_BOX, WXRESIZE_BOX, WXSYSTEM_MENU, and WXCAPTION combination. WXICONIZE Displays a window (for Windows only) WXCAPTION Title WXMINIMIZE and WXCONIZE WXMINIMIZE_BOX Framework will have a minimize button WXMAXIMize framework to maximize the way (for Windows) wxmaximize_box framework will have a maximum button WXSTAY_ON_TOP The frame will have a system menu with the upper layer (for Windows) wxsystem_menu frames located in other windows. wxSIMPLE_BORDER a display without a frame border (only GTK with Windows) wxRESIZE_BORDER display a resizable border (only with Unix) wxFRAME_FLOAT_ON_PARENT The frame will be above the parent window in the z-order and is not shown in the task Bar. (Windows and gtk only) wxframe_tool_window Displays a small title bar (for Windows only) Name is the name of the window. This parameter is used to associate an entry with a name. This allows the user to set the MOTIF resource value for each window.
Example 2.3 and Example 2.4 are the implementation of the program
2.3. TEXTEDITORAPP.H - TEXTEDITORAPP definition
#ifndef texteditorapp_h #define texteditorapp_h Class TextEditorapp: public wxapp {public: / ** * Program initialization * / virtual bool oninit ();}; declare_app (texteditorapp) #ENDIF // TextEditorapp_h
Example 2.4. TEXTEDITORAPP.CPP - TEXTEDITORAPP implementation
/ / To support the pre-compilation compiler, "wx / wx.h" #include "wx / wxprec.h" #ifndef wx_precomp #include "wx / wx.h" #ENDIF #include "textEDITORAPP.H" #includ " TextFrame.h "IMPLEMENT_APP (TextEditorApp) bool TextEditorApp :: OnInit () {TextFrame * frame = new TextFrame (" Simple Text Editor ", 100, 100, 400, 300); frame-> Show (TRUE); SetTopWindow (frame) Return True;}
Add control
A window frame is now created, you need to add some controls to process text. Class WXTextCtrl will be what we need. The framework class already contains this control.
Example 2.5 is a definition of a new TEXTFrame class. Only one thing is changing, it adds a member of a wxtextCtrl type. This member is initialized in the constructor.
Example 2.5. TEXTFRAME redefine
#ifndef _TEXTFRAME_H #define _TEXTFRAME_H class TextFrame: public wxFrame {public: / ** * constructor to create a new TextFrame * / TextFrame (const wxChar * title, int xpos, int ypos, int width, int height); /. ** * Destructor * / ~ textFrame (); private: wxtextCtrl * m_ptextctrl;}; # endif // _ textframe_h
Example 2.6 is a constructor of the updated TextFraem class. TextFrame is the parent class of WXTextCtrl members. So you should pass the THIS pointer. String "Type Some Text ..." will be used as the default text. Note that the constructor of WXTextCtrl looks like WXFrame. This is because each class is inherited from wxwindow, so there is the same constructor mode.
Also, the code of the WXTextCtrl pointer is not deleted here. It doesn't matter here (actually not allowed), because all subclasses of it will automatically delete when the parent class textFrame is undo.
WXTE_MULTILINE is a dedicated window style for text controls. This style indicates that WXTextCtrl allows you.
Example 2.6.TextFrame Implementation
/ / To support the preparatory compiler, "wx / wx.h" #include "wx / wxprec.h" #Ifndef wx_precomp #include "wx / wx.h" #ENDIF #include "textframe.h" textframe :: TEXTFRAME (Const WxChar * Title, INT XPOS, INT YPOS, INT WIDTH, INT Height): wxframe (wxframe *) NULL, -1, TITLE, WXPOINT (XPOS, YPOS), WXSIZE (WIDTH, HEIGHT) {m_ptextCtrl = New wxtextCtrl (this, -1, wxstring ("Type Some text ..."), wxdefaultposition, wxdefaultsize, wxte_multiline);} textframe :: ~ textFrame () {}
When you build this project, you will have a window that you can enter some text, you can try to cut in this window, paste the text, you will have these short code has made a lot of things for you.
Add a menu bar
Typically, we always add a menu bar to help the user manager, wxWindows provides the following classes: WXMenubar and WxMenu.
Each menu requires a separate ID. This is done by an enumerated type. Can't use the constant defined by #define (such as: #define menu_file_meu 1) because this cannot guarantee that you have a unique ID. It is very easy to miss out and it will become more difficult to maintain when you want to insert a new ID.
Please refer to the wxwindows manual, wxwin predefined some IDs you use when using document / view Framework.
Example 2.7. Definition of TextFrame
#ifndef _TEXTFRAME_H #define _TEXTFRAME_H class TextFrame: public wxFrame {public: / ** * Constructor Creates a new TextFrame * / TextFrame (const wxChar * title, int xpos, int ypos, int width, int height); / ** *. destructor * / ~ TextFrame (); private: wxTextCtrl * m_pTextCtrl; wxMenuBar * m_pMenuBar; wxMenu * m_pFileMenu; wxMenu * m_pInfoMenu; enum {MENU_FILE_OPEN, MENU_FILE_SAVE, MENU_FILE_QUIT, MENU_INFO_ABOUT};}; #endif // _ TEXTFRAME_H menu bar in the TextFrame Created in the constructor. A menu item is added to the menu using the Append method of wxmenu. Pay attention to how the number indicates which character is shortcut. When you are created, you should add it to the menu bar using wxmenubar.
Example 2.8. TEXTFRAME
// for Compilers That Supports precompilation, include "wx / wx.h" #include "wx / wxprec.h" #1ndef wx_precomp #include "wx / wx.h" #ENDIF #include "textframe.h" textframe :: textframe :: TextFrame (Const WxChar * Title, int XPOS, INT YPOS, INT WIDTH, INTHEIGHT: WXFrame (wxframe *) NULL, -1, TIS, WXPOINT (XPOS, YPOS), WXSIZE (WIDTH, HEIGHT) {m_ptextctrl = New wxTextCtrl (this, -1, wxString ( "Type some text ..."), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE); m_pMenuBar = new wxMenuBar (); // File Menu m_pFileMenu = new wxMenu (); m_pFileMenu-> Append (MENU_FILE_OPEN , "& Open"); m_pfileMenu-> append (Menu_File_Save, "& Save"); m_pfileMenu-> appendseparator (); m_pfileMenu-> append (menu_file_quit, "& quit"); m_pmenubar-> append (m_pfilemenu, "& file"); / / About menu m_pInfoMenu = new wxMenu (); m_pInfoMenu-> Append (MENU_INFO_ABOUT, "& About"); m_pMenuBar-> Append (m_pInfoMenu, "& Info"); setMenuBar (m_pMenuBar);} TextFrame :: ~ TextFrame () {}
Add status bar
It is easy to add a status bar for the frame. Using the CreateStatusBar method in the wxframe class to create a status bar, it accepts a shaping parameter as the number of zones in the status bar, using the SetStatusText method to change the text content in each domain. EXAMPLE 2.9. Creation of the status bar
CreateStatusbar (3); SetStatustext ("Ready", 0);
EXAMPLE 2.9 Create a status bar with three domains. The first domain contains text "ready".
The status bar can be used to display a description of a menu item. Example 2.10 changes to Example 2.8 for adding menu items to the menu bar in the previous section to enable the menu item to associate with the status bar. When a menu item is selected, the relevant description is displayed in the first domain in the status bar.
Example 2.10 The menu item containing the function
// File menu
M_PfileMenu = new wxmenu ();
m_pfileMenu-> append (menu_file_open, "& open", "opens an existing file");
m_pfilemenu-> append (menu_file_save, "& savior", "save the content");
m_pfilemenu-> appendseparator ();
m_pfileMenu-> append (menu_file_quit, "& quit", "quit the application");
m_pmenubar-> append (m_pfilemenu, "& file");
/ / About menu
m_pinfomenu = new wxmenu ();
m_pinfomenu-> append (menu_info_about, "offer", "shows information about the application);
m_pmenubar-> append (m_pinfomenu, "& info");
Handling menu event
Now there is already a menu on the frame, when the user chooses a menu, we have to use a method to implement its corresponding action. Each event will generate an event. How to make a movement associated with this event? A trick is to associate a class method with an event. In the early versions of WXWindows, this is achieved by using a callback function or by overloading virtual functions. Change from WXWindows 2.0 to use the event table. In this section we only explain the events generated by the menu. The detailed process of incident processing We will explain it in Chapter 3.
Each class to deal with the event needs to declare an event table. Macro DECLARE_EVENT_TABLE is used to complete this work. Every event must have a method that has already been implemented. Each method has a parameter to contain information. The event obtained from the menu is a wxcommandevent type data. Example 2.11 is a complete definition of class TextFrame.
Example 2.11. Complete Definition of TextFrame.h
. #Ifndef _TEXTFRAME_H #define _TEXTFRAME_H class TextFrame: public wxFrame {public: / ** * Constructor Creates a new TextFrame * / TextFrame (const wxChar title, int xpos, int ypos, int width, int height); / ** * Destructor * / ~ TextFrame (); / ** * Processes menu File | Open * / void OnMenuFileOpen (wxCommandEvent & event); / ** * Processes menu File | Save * / void OnMenuFileSave (wxCommandEvent & event); / ** * Processes menu File | Quit * / void OnMenuFileQuit (wxCommandEvent & event); / ** * Processes menu About | Info * / void OnMenuInfoAbout (wxCommandEvent & event); protected: DECLARE_EVENT_TABLE () private: wxTextCtrl * m_pTextCtrl; wxMenuBar * m_pMenuBar; wxMenu * m_pFileMenu; wxMenu * m_pinfomenu; enum {menu_file_open, menu_file_save, menu_file_quit, menu_info_about};}; #ENDIF / / TEXTFRAME_H Event Table is in realization, WXWindows completes the statement of the event table by some macro. Macro BeGin_Event uses the beginning of an event table declaration because there may be more than one event table in a program to pass the class name related class name to the macro. Use an EVT_MENU macro to associate a method with an event. This macro requires a menu ID and an event name. At the end of the event table, the end tag is ended with the macro end_event_table. Example 2.12 shows a complete implementation file.
Example 2.12. TextFrame.cpp - The Full Implementation
// for Compilers That Supports precompilation, include "wx / wx.h" #include "wx / wxprec.h" #1ndef wx_precomp #include "wx / wx.h" #ENDIF #include "textframe.h" textframe :: textframe :: TextFrame (Const WxChar * Title, int XPOS, INT YPOS, INT WIDTH, INTHEIGHT: WXFrame (wxframe *) NULL, -1, TIS, WXPOINT (XPOS, YPOS), WXSIZE (WIDTH, HEIGHT) {m_ptextctrl = New wxTextCtrl (this, -1, wxString ( "Type some text ..."), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE); CreateStatusBar (); m_pMenuBar = new wxMenuBar (); // File Menu m_pFileMenu = new wxMenu (); m_pFileMenu- > Append (MENU_FILE_OPEN, "& Open", "Opens an existing file"); m_pFileMenu-> Append (MENU_FILE_SAVE, "& Save", "Saves the file"); m_pFileMenu-> AppendSeparator (); m_pFileMenu-> Append (MENU_FILE_QUIT, " & Quit, "Close the application"); m_pMenuBar-> Append (m_pFileMenu, "& File"); // About menu m_pInfoMenu = new wxMenu (); m_pInfoMenu-> Append (MENU_INFO_ABOUT, "& About", "Shows info about the application" ); m_pmenubar-> append (m_pinfomenu, "& info"); setmenubar (m_ pMenuBar);} TextFrame :: ~ TextFrame () {} BEGIN_EVENT_TABLE (TextFrame, wxFrame) EVT_MENU (MENU_FILE_OPEN, TextFrame :: OnMenuFileOpen) EVT_MENU (MENU_FILE_SAVE, TextFrame :: OnMenuFileSave) EVT_MENU (MENU_FILE_QUIT, TextFrame :: OnMenuFileQuit) EVT_MENU (MENU_INFO_ABOUT, TextFrame :: OnMenuInfoAbout) END_EVENT_TABLE void TextFrame :: OnMenuFileOpen (wxCommandEvent & event) {wxLogMessage ( "File Open Menu Selected");} void TextFrame :: OnMenuFileSave (wxCommandEvent & event) {wxLogMessage ( "File Save Menu Selected");
} Void TextFrame :: OnMenuFileQuit (wxCommandEvent & event) {Close (FALSE);} void TextFrame :: OnMenuInfoAbout (wxCommandEvent & event) {wxLogMessage ( "File About Menu Selected");} Chapter Event Processing
table of Contents
Introduction
How is it working?
Event jump
Incident
Handle
In the previous chapter, I have learned how to deal with menu events. This chapter will explain how the event is working, while explaining how to deal with other events.
Introduction Introduction
The event is something that appears inside or outside the program. An event may be triggered by a user or other programs, an operating system, or the like. At this time, a mechanism is required to let the program respond to the expected event.
In earlier versions of WXWindows, the program's event processing is completely implemented through a callback function or an overloaded virtual function. Use the incident table from WXWindows 2.0 to use the event table. As in Example 3, the event table tells wxwindows to map events to member functions. The event table is declared in the implementation of the file (CPP).
Example 3.1. Event Table
Begin_Event_Table (MyFrame, wxframe) EVT_MENU (wxid_exit, myframe :: onexit) evt_size (myframe :: onsize) evt_button (Button1, Myframe :: OnButton1) end_event_table ()
The above incident table tells wxwindows call myFrame's member function onSize when it receives a WM_SIZE event. Macro Begin_Event_Table declares that wxframe and its subclass MyFrame have this incident table.
The members of the handling event cannot be virtual. In fact, the event processor will ignore the virtual statement. The event handler has a similar form: return types of VOID and accepts an event parameter. The type of this parameter is related to the specific event. For Size events, the type used is wxcommandevent. When the control is more complicated, they use their own event classes.
In the class definition, there must be a declare_event_table macro. See Example 2.11.
All of these macros hide complex event processing systems.
How did it work?
When an event is received, WXWindows first invokes the procssEventLler of WXEventHandler on the object on the window. WXWindow (and other window classes) inherit from WXEventHander. ProcessEvent Finds every event in the event table and calls zero or multiple event processor functions. Below is the step of processing an event:
When the object is turned off (including the setvthandle) function of WXEVTHANDLER, you jump to the sixth step. If the object is a wxwindow object, Processevent is handed over on the wxvalidator of the window. If the return function is exited. SearcheventTable is a function of the event processor call. When it fails, starting at the base class until there is no more event table or finding a suitable function. This function exits. The found function begins. The lookup process is applied to the entire event processor chain, and when the application is successful (indicating the event processing) function exits. When the object is a wxwindow object, and the event is the WXCommandEvent type, ProcessEvent is recursively used to the event processor applied to the parent window. When it returns true, the function exits. This allows a button's father to handle the click of the button instead of letting the button hand it yourself. Finally, Processevent is called on the WXAPP object.
Event jump EVENT SKENT SKIPPING
Processevent exits after discovering a function that can handle events. This means that when your class reacts to an event, the next class will not get this event. Sometimes we don't want this. This problem can be solved with the Skip method of the WXEvent class according to the basic type of the base class, so that the event processor's lookup continues. The following example shows the use of event jumps. Example 3.2 is a definition of a text control that only accepts numeric characters.
Example 3.2. NumTextCtrl.h
Class NumTextCtrl: public wxtextCtrl {public: NumTextCtrl (wxwindow * parent); void onchar (wxkeyevent & evenet); protected: declare_event_table ()};
When NumericTextCtrl receives a keyboard event, KEYCODE check is performed. If you entered a number, base class wxtextCtrl can handle this event. This is why we want to use jump on this event. You must call the SKIP method here, otherwise the base class does not process any keys.
Example 3.3. NumTextCtrl.cpp
// for Compilers That Supports precompilation, include "wx / wx.h" #include "wx / wxprec.h" #ifndef wx_precomp #include "wx / wx.h" #ENDIF #include "numTextCtrl.h" #include
Incident
Some events are disabled. This event will not be further processed when you prohibit an event. Example 3.4 Demo, how to disable this simple text editor after the text changes in a text control. This means that this window cannot be turned off when the user has not saved the changed text content.
Example 3.4. Prohibited event
void TextFrame :: OnClose (wxCloseEvent & event) {bool destroy = true;! if (event.CanVeto ()) {if (m_pTextCtrl-> IsModified ()) {wxMessageDialog * dlg = new wxMessageDialog (this, "Text is changed / nAre YOU SURE You Want TO EXIT? "," Text Changd !!! ", wxyes_no | wxno_default); int result = DLG-> ShowModal (); if (result == wxid_no) {Event.veto (); design; = false; }}}} {destroy ();} What is the program when Canveto returns false? You will not ban this event, your program will exit.
Blocking event processor Plug An Event Handler
Consider the following problem: Each menu command must be recorded. A solution is to create a function called in each command event handler. The problem brought about this method is to make maintenance very difficult. This menu command will not be recorded when adding a new menu and does not call this function.
Solving this problem is to create a new event processor and add to a wxwindow class. To complete it needs to create a new class derived from WXEvthandler. Processing in the new class is the same as a normal window.
Example 3.5. LogeventHandler.h -LogeventHandler definition
#ifndef _LogEventHandler_H #define _LogEventHandler_H class LogEventHandler: public wxEvtHandler {public: LogEventHandler (): wxEvtHandler () {} virtual ~ LogEventHandler () {} protected: DECLARE_EVENT_TABLE () void OnMenu (wxMenuEvent & event); private:}; #endif // _LOGEVENTHANDLER_H
Example 3.6. LOGEVENTHANDLER.CPP - LOGEVENTHANDLER
// for Compilers That Supports precompilation, include "wx / wx.h" #include "wx / wxprec.h" #ifndef wx_precomp #include "wx / wx.h" #ENDIF #include "LOGEVENTHANDLER.H" Void Logeventrandler :: OnMenu (wxMenuEvent & event) {wxLogMessage ( "Someone selected a item menu"); event.Skip ();} BEGIN_EVENT_TABLE (LogEventHandler, wxEvtHandler) EVT_MENU_RANGE (-1, -1, LogEventHandler :: OnMenu) END_EVENT_TABLE ()
In the macro evt_menu_range, all menu events can be processed. The first two parameters are used to specify the ID range of the menu to be processed. -1 represents all menu items. Don't forget to call Skip on the event, otherwise there will be no events pass to the event processor of class wxwindow.
The next step is to press the new event processor into the processor stack. This is done using WXWindow's PUSHEVENTHANDLER. To remove the event processor from the stack Using PopeventHandler. PusheventHandler (New LogeventHandler ());
PopeventHandler has a Boolean parameter that is true when this parameter is true, WXWindows deletes event processors. Note When there is no event processor being taken out, WXWndows will try to delete the event processor when the window will undo. This occurs an access error when accessing an event processor created on the stack. This issue can be avoided before a class revoked PopeVentHandler can avoid this problem.
Chapter 4. General dialog
Table of contents
WXFiledialog
Constructor
Methods
EXAMPLE
WXFileSelector
WXCOLOURDIALOG
Constructor
Methods
WxcolourData
EXAMPLE
WxgetCOLOURFROMUSER
WXFONTDIALOGOG
Constructor
Methods
WXFONTDATA
EXAMPLE
WXPrintDialog
Constructor
Methods
EXAMPLE
WXDIRDIALOG
Constructor
Methods
EXAMPLE
WXDIRSELECTOR
WXTEXTENTRYDIALOGOGOG
Constructor
Methods
EXAMPLE
WxgetTextFromuser
WxGetPasswordFromuser
WxMessageDialog
Constructor
Methods
EXAMPLE
WxMessageBox
WXSinglechoiceDialog
Constructor
Methods
EXAMPLE
Wxgetsinglechoice
WxgetsinglechoiceIndex
WxgetsinglechoiceData
In the example of the second chapter, there is a menu command to open and store a text file. At this point, you should use a general dialog wxfiledialog to allow users to select or enter a file name. When using a general dialog, the user gets a unified interface. This allows users to see similar dialogs regardless of what kind of programs.
WXWindows offers the following general dialogs.
WXFiledialog is a dialog box that stores or opens a file. WXCOLOURDIALOG a selection color dialog. WXFONTDIALOG Select the dialog box. WXPrintDialog is used to print a dialog box for setting up printers. WXDIRDIALOG selection directory dialog box. WXTEXTENTRYDIALOG requests a user into a dialog box for a line. WxMessageDialog is used to display a row or multi-line information, which can include OK, Yes, NO, with the Cancel button. WXSINGLECHOICEDIALOG displays a dialog box containing a string list and allows users to select one.
WXWindows is the Framework for cross platforms. WXWindow will display a general dialog when a general dialog box cannot be used on a particular platform.
note
In the example of each dialog box below, the Destroy method will be used instead of the method of deleting pointers to undo the window. This is for a stable purpose. WXWindows controls should always be created on the heap and use the Destroy method to be safely removed. Because wxwindows sometimes deletes until all events are processed. This way WXWindows avoids sending events to a window that does not exist.
WXFiledialog
WXFiledialog provides users with a dialog box that can select or enter a file name when a user is turned on or stored. A global method WXFileSelector can also be used to allow users to choose a file. For details, please see the section "wxfileselector". Constructor
#include
wxFileDialog (wxWindow * parent, const wxString & message = "Choose a file", const wxString & defaultDir = "", const wxString & defaultFile = "", const wxString & wildcard = "", long style = 0, const wxPoint & pos = wxDefaultPosition);
PARENT has a window of this dialog. The headline of the message dialog. DefaultDir default directory. Defaultfile default file name. Wildcard is some strings like "*. *" * .txt ". This is used to filter files. Its syntax is description | suffix. Example "All Files (*. *) | *. * | Text files (*. Txt) | * .txt | Bitmap files (*. Bmp) | * .bmp". Style dialog. Table 4.1. Wxfiledialog style
WXChange_dir change the current directory wxfile_must_exist Enter file must exist that WXHIDE_READOONLY hide read-only file wxmultiple is just an open dialog, allowing multiple files to be selected. WxOpen is just an open dialog. WxOverWrite_Prompt is determined when a file will overwrite. WXSave a save dialog. POS is not used.
method
Public void setDirectory (const wxstring & dir); public wxstring getdirectory ();
Set with your current directory
Public void setFileName (const wxstring & name); public wxstring getFileName ();
Set with get the current file name
Public const void getFilenames (wxaRrayString & Files);
Use the selected file name to add a file name array. This function is only used for WXMultiPle dialogs. Other use GetFileName.
Public void setfilterindex (int filterindex); public int getFilterIndex ();
Set the index with the list of filters given. The filter is first used when the dialog is displayed before the dialog box is displayed. This index is selected by the user after display.
Public Void SetMessage (Const WxString & Message); Public wxString getMessage ();
Set the title to the new dialog box.
Public void setpath; public wxstring getpath ();
Set with the current path (directory and file name)
Public void setStyle (long style); public long getStyle ();
Set the style to get the dialog box, see "constructor"
Public void getPaths (wxaRrayString & paths); populate the path array with the selected file absolute path name. This function is only used for WXMultiPle dialogs. Other use getPath.
Public void setwildcard; public wxstring getWildcard ();
Set with getting Wildcard See "Constructor".
Public int showModal ();
The dialog box is displayed and returns WXID_OK when the user presses OK. Other situations return wxid_cancel.
example
In the text editor example of the second chapter, use ShowModal to display a dialog. "MODAL" means that other windows of the program before the dialog is closed, you cannot get the focus. When using the ShowModal display dialog, return wxid_ok when the user presses OK. Other situations return wxid_cancel. GetFileName is the file name used to get the selected file. GetPath will return the full path (directory and file name) of the selected file. Loading and saving files is very simple when using WXTextCtrl controls. Method LoadFile and Savefile are used to load and save files, respectively.
Example 4.1. WXFiledIalog
Void textframe :: onmenufileopen (wxcommandevent) {wxfiledialog * DLG = New WXFiledialog (this, "Open a text file", ",", "all files (*. *) | *. * | text files (*. TXT) | * .txt ", wxopen, wxdefaultposition); if (dlg-> showmodal () == wxid_ok) {m_ptextctrl-> loadingfile (DLG-> getFileName ()); setStatustext (dlg-> getFileName (), 0) DLG-> destroy ();} void textframe :: OnMenuFilesave (wxcommandevent & evenet) {wxfiledialog * DLG = New wxfiledialog (this, "save a text file", ",", "all files (*. *) | *. * | Text files (*. Txt) | * .txt ", wxsave, wxdefaultposition); if (dlg-> showmodal () == wxid_ok) {m_ptextctrl-> savefile (DLG-> getPath ()); setStatusText (DLG-> getFilename (), 0);} DLG-> destroy ();
WXFileSelector
WXFileSelector pops up a file selection box. Returns an empty string when the user ignores it.
wxString wxFileSelector (const wxString & message, const wxString & defaultPath = "", const wxString & defaultFile = "", const wxString & defaultExtension = "", const wxString & wildcard = "*. *", int flags = 0, wxWindow * parent = NULL, int X = -1, int y = -1); the title of the Message file selector. DefaultPath Default Path I DefaultFile Default File Default The default suffix. This suffix will be automatically added to the file when the user omits the suffix. WXWindows automatically adds a filter when not specified by Wildcard. Wildcard (see wxfiledialog constructor). Flags is the style of the dialog. See WXFiledIalog constructor. The X-axis position of the WXMultiPle style Parent parent window X selector is not supported. The Y-axis position of the Y selector.
example
Example 4.2 Requires Users Select a JavaScript file.
Example 4.2. Use of WXFileSelector.
WXString Selection = WXFileSelector ("Open A JavaScript file", ",", "js", "all files (*. *) | *. * | javascript files (*. js) | * .js | Text Files * .txt) | * .txt ", wxopen, this);
WXCOLOURDIALOG
WXCOLOURDIALOG implements a window for users to choose color. WXCOLOURDIALOG is used in common with WXCOLOURDATA. WXCOLOURDATA is used to set the current color in the dialog and to get selected colors.
Constructor
#include
WXCOLOURDIALOG (WXWindow * Parent, wxcolourdata * data = null);
Parent i is the parent window of our dialog. DATA contains color information. It includes default colors, custom colors, and under Windows you can tell it to display a population dialog that contains a custom color selection control.
method
Public wxcolourdata & getColourData ();
Get reference to the Coloudata associated with this dialog.
Public void settitle (const wxstring & title); public wxstring gettitle ();
Set or get the title of the dialog
Public int showModal ();
The dialog box is displayed and returns WXID_OK when the user presses OK. Other situations return wxid_cancel.
WxcolourData
This class contains information related to WXCOLOURDIALOG.
Constructor
WXCOLOURDATA ();
Default constructor
WXCOLOURDATA (Const WxcolourData & Data);
Copy constructor
method
Public void setchoosefull (bool flag); public bool getchoosefull ();
On Windows, this method displays a dialog that contains a custom color selection control, the default value is TRUE.
Public void setcolour (wxcolour & color); public wxcolour & getColour ();
Set or get the selected color.
Public Void SetCustomColour (INT I, WXCOLOUR & COLOUR); Public WxColour GetCustomColour (INT I);
Set or get a custom color of a given location. I must be between 0 and 15.
example
Example 4.3 Add a menu item to the program to allow users to select other background colors. The current background colors are given to colourData. If the program is running under Windows, a population dialog will appear.
Example 4.3. WXCOLOURDIALOG
void TextFrame :: OnMenuOptionBackgroundColor (wxCommandEvent & event) {wxColourData colourData; wxColour colour = m_pTextCtrl-> GetBackgroundColour (); colourData.SetColour (colour); colourData.SetChooseFull (true); wxColourDialog * dlg = new wxColourDialog (this, & colourData); if (DLG-> showModal () == wxid_ok) {colorData = DLG-> getColourData (); m_ptextctrl-> setBackgroundColour (); m_ptextctrl-> refresh ();} DLG-> destroy ();
WxgetCOLOURFROMUSER
WxGetCOLOURFROMUSER Displays the color selection dialog and returns the color selected by the user or returns an invalid color when the user cancels the dialog. Test the color is valid using WXCOLOUR OK method.
WXCOLOUR WXGETCOLOURFROMUSER (wxwindow * parent = null, const wxcolour & colinit = wxnullcolour);
The parent window of the PARENT selector. Colinit initial colors.
example
Example 4.4 To show a user to choose a color
Example 4.4. WXGETCOLOURFROMUSER
wxcolour color = wxgetColourFromuser (); if (color.ok ()) {// user selection color}
WXFONTDIALOGOG
WXFontDialog is a dialog for users to select fonts. This dialog is used with wxfontdata, wxfont, and wxcolour. WXFontData is used to set the current font within the dialog and get the font.
Constructor
#include
WXCOLOURDIALOG (WXWindow * Parent, wxfontdata * data = null);
The parent window DATA of the Parent dialog box contains font. It contains information such as default fonts, current font colors.
method
Public wxfontdata & getfontdata ();
Get reference to the FontData associated with the dialog.
Public int showModal ();
The dialog box is displayed and returns WXID_OK when the user presses OK. Other situations return wxid_cancel. WXFONTDATA
WXFONTDATA ();
Default constructor
Public void enableeffects (Bool flag); public bool getenableeffects;
On Windows, it is pointed out whether the font effect is used, such as underline, italic, and the like.
Public void setallowsymbols (bool flag); Public Bool getAllowsymbols ();
On Windows, indicating whether the symbol font can be selected.
Public void setColour; Public wxcolour & getcolour ();
Set or get the font color.
Public void setshowhelp (bool flag); public bool getshowhelp ();
ON on Windows, pointing to whether the Help button is displayed.
Public void setInitialFont (const wxfont & font); public wxfont getinitialfont ();
Get or set the original font used by the dialog.
Public wxfont getChosenfont ();
Get the selected font.
Public Void SetRange (int minrange, int maxRANGE);
On Windows, pointing out the maximum and minimum of the font size. By default, 0 to infinite.
example
Example Example 4.5 implements a new menu item to change the font within the editor. First, fontdata fills with the current font and color, when the program is running on Windows, the user will see the help button. When the user selects the font, FontData will be assigned to the foreground color of the new font and the text control.
Example 4.5. WXFONTDIALOG
void TextFrame :: OnMenuOptionFont (wxCommandEvent & event) {wxFontData fontData; wxFont font; wxColour colour; font = m_pTextCtrl-> GetFont (); fontData.SetInitialFont (font); colour = m_pTextCtrl-> GetForegroundColour (); fontData.SetColour (colour) FONTDATA.SETSHOWHELP (TRUE); WXFONTDIALOG * DLG = New wxfontdialog (this, & fontdata); if (DLG-> ShowModal () == wxid_ok) {fontdata = DLG-> getFontData (); font = fontdata.getchosenfont (); M_PTextCtrl-> setFont (font); m_ptextctrl-> setForegroundColour (fontdata.getcolour ()); m_ptextctrl-> refresh ();} DLG-> destroy ();
WXPrintDialog
Todo.
Constructor
Methods
EXAMPLE
WXDIRDIALOG
WXDIRDIALOG is used to select a directory
Constructor
#include
wxDirDialog (wxWindow * parent, const wxString & message = "Choose a directory", const wxString & defaultPath = "", long style = 0, const wxPoint & pos = wxDefaultPosition); parent parent window pointer message header DefaultPath default path style does not use pos not used
method
Public Void SetMessage (Const WxString & Message); Public wxString getMessage ();
Get the title of setting dialog
Void setPath (Const WxString & Path); Public wxString getPath ();
Get with setting the current path
Public int showModal ();
The dialog box is displayed and returns WXID_OK when the user presses OK. Other situations return wxid_cancel.
example
Example 4.6 shows the implementation of the menu movement to set the new work directory. WxGetCWD is used to get the current working directory. When the user selects a directory you can use the getPath method to get the directory name. WXSetworkingDirectory is used to set up a new work directory.
Example 4.6. WXDIRDIALOG.
void TextFrame :: OnMenuOptionDirectory (wxCommandEvent & event) {wxDirDialog * dlg = new wxDirDialog (this, "Select a new working directory", wxGetCwd ()); if (dlg-> ShowModal () == wxID_OK) {wxSetWorkingDirectory (dlg-> GetPath ());} DLG-> destroy ();
WXDIRSELECTOR
WXDIRSELECTOR pops up a directory selection box.
WXSTRING WXDIRSELECTOR (Const WxString & Message, Const WxString & DEFAULTPATH = "", long style = 0, const wxpoint & pos = wxdefaultPosition, wxwindow * parent = null);
Message Title The DefaultPath default path i style dialog, see the WXDIRDIALOGIS POS dialog position. Parent parent window.
example
Example 4.7 requires a user to select a folder.
Example 4.7. Using WXDIRSELECTOR
WXSTRING Selection = WXDIRSELECTOR ("SELECT A Folder"); if (! selection.empty ()) {// The user selected a folder.
WXTEXTENTRYDIALOGOGOG
WXTEXTENTRYDIALOG requests a user into a dialog box for a line.
Constructor
#include
wxTextEntryDialog (wxWindow * parent, const wxString & message, const wxString & caption = "Please enter text", const wxString & defaultValue = "", long style = wxOK | wxCANCEL | wxCENTRE, const wxPoint & pos = wxDefaultPosition); parent parent window. The information displayed in the Message dialog box. DefaultValue Default Text. The Caption Title Style dialog. You can use WXTextCtrl style. Table Table 4.2. WXTEXTENTRYDIALOG style styles
WXCancel Displays the Cancel Button Wxcentre Central Dialog WXOK Displays the location of the OK button POS dialog
method
Void SetValue (Const WxString & Val); Public WXString getValue ();
Get the value of the set text area. Get / set the value of the text field.
Public int showModal ();
The dialog box is displayed and returns WXID_OK when the user presses OK. Other situations return wxid_cancel.
example
Example 4.8 Display a dialog prompting the user to enter a password.
Example 4.8. WXTEXTENTRYDIALOG
wxTextEntryDialog * dlg = new wxTextEntryDialog (this, "Enter your password", "Enter your password", "", wxOK | wxCANCEL | wxCENTRE | wxTE_PASSWORD); if (dlg-> ShowModal () == wxID_OK) {// Check the Password} else {// stop the application} DLG-> destroy ();
WxgetTextFromuser
WxgetTextFromuser pops up a dialog that allows users to enter some text.
wxString wxGetTextFromUser (const wxString & message, const wxString & caption = "Input text", const wxString & defaultValue = "", wxWindow * parent = NULL, int x = -1, int y = -1, bool centre = true);
The information displayed in the Message dialog box. In the information, you can include a wrap Caption title DEFAULTVALUE default text. Parent parent window. The X-axis position Y spindle position of the X dialog box. Center: At the center of the true time dialog, other situations are left.
example
Example 4.9 requires a user to enter some text. a
Example 4.9. WXGetTextFromuser's use
WXString text = wxgetTextFromuser ("please, enter Some text");
WxGetPasswordFromuser
WxGetPasswordFromuser pops up a dialog box for entering a password.
WXString WxGetPasswordFromuser (const wxstring & copy = "input text", const wxstring & defaultValue = ", wxwindow * parent = null);
The information displayed in the Message dialog box. In the information, you can include a wrap Caption title DEFAULTVALUE default text Parent parent window
example
EXAMPLE 4.10 Require User Enter Password
Example 4.10. WXGETPASSWORDFROMUSER
WXSTRING PWD = WXGetPasswordFromuser ("please, enter you password");
WxMessageDialog
WxMessageDialog can be used to display a row or multi-line information, which can contain OK, Yes, NO or Cancel buttons.
Constructor constructor
#include
WxMessageDialog (wxwindow * parent, const wxstring & copy = "message box", long style = wxok | wxcancel | wxcentre, const wxpoint & pos = wxdefaultPosition;
Parent parent window. The information displayed in the Message dialog can be multi-line text. Caption title. Style dialog in style. Table 4.3. WxMessageDialog style. Styles
WXOK displays OK button. wxcancel displays Cancel Button. wxyes_no Displays YES and NO buttons. WXYES_DEFALT uses wxyes_no to let Yes buttons as the default button. This is the default behavior. WXNO_DEFAULT USED with WXYES_NO, let the NO button are default. WXCENTRE Let the information are located in the center, not the window located in the center. WXICON_EXCLAMATION displays an exclamation mark icon. WXICON_HAND displays an error icon. WXICON_ERROR is the same. WXICON_QUESTION shows the question mark icon. WXICON_INFORMATION Display Information (i) icon. The position of the POS dialog box.
Methods method
Public int showModal ();
The dialog box is displayed and returns WXID_OK when the user presses OK. Other situations return wxid_cancel.
example
Example 3.4 Displays WXMessageDialog asks if the user really exits the program.
WxMessageBox
WxMessageBox displays a message. The return value is one of wxyes, wxno, wxcancel, wxok.
WxMessageBox (const wxstring & copy = "message wxstring & caption =" message box ", int style, wxock | wxcent, wxwindow * parent, int x = -1, int y = -1); message displayed. Caption Title Style style. See the WXMessageDialog Parent Parent window. X x axis position. Y Y axis position.
Note Note
Local MessageBox functions on Windows are not using wxcentre style. In the general function, it is used. This is because local functions cannot be centered in text. The symbol is not displayed when the generic function is used.
WXSinglechoiceDialog
Constructor constructor
#include
wxSingleChoiceDialog (wxWindow * parent, const wxString & message, const wxString & caption, int n, const wxString * choices, char ** clientData = (char **) NULL, long style = wxCHOICEDLG_STYLE, const wxPoint & pos = wxDefaultPosition);
Parent parent window. The information displayed in the Message dialog box. Caption title. n entry number. Choices is a string array. ClientData style dialog style. Table 4.4. WXSinglechoiceDialog style
WXOK displays ok button. wxcancel displays Cancel Button. Wxcentre hits the information in non-Windows. WXCHOICEDLG_STYLE WXOK | WXCANCEL | WXCENTRE POS dialog box.
Methods method
Public void setSelection (int SEL);
Set option
Public int getselection ();
Returns the option of the option.
Public wxstring getstringselection ();
Returns the option.
Public int showModal ();
The dialog box is displayed and returns WXID_OK when the user presses OK. Other situations return wxid_cancel.
example
An example shows a dialog to let users choose their country.
Example 4.11. WXSINGLECHOICEDIALOG is used.
WXString Countries [] = {"Belgium", "United Kingdom", "USA", "France"}; wxsinglechoiceDialog * DLG = New WXSINGLEDIALOG * DLG = New WXSINGLEDIALOG (NULL, "Where do you live?", "SELECT A Country", 4, Countries ); if (DLG-> showModal () == wxid_ok) {wxMessageBox ("you live in" DLG-> getStringSelection ());} DLG-> Destroy (); wxgetsinglechoice
WXGetSinglechoice displays wxsinglechoiceDialog and returns the selected string.
wxString wxGetSingleChoice (const wxString & message, const wxString & caption, const wxArrayString & choices, wxWindow * parent = (wxWindow *) NULL, int x = -1, int y = -1, bool centre = TRUE, int width = wxCHOICE_WIDTH, int height = wxchoice_height);
wxString wxGetSingleChoice (const wxString & message, const wxString & caption, int n, const wxString * choices, wxWindow * parent = (wxWindow *) NULL, int x = -1, int y = -1, bool centre = TRUE, int width = wxCHOICE_WIDTH , Int Height = wxchoice_HEIGHT);
WxgetsinglechoiceIndex
WxgetSinglechoiceIndex displays wxsinglechoiceDialog and returns the selected index. Returns -1 when no option is selected.
int wxGetSingleChoiceIndex (const wxString & message, const wxString & caption, const wxArrayString & choices, wxWindow * parent = (wxWindow *) NULL, int x = -1, int y = -1, bool centre = TRUE, int width = wxCHOICE_WIDTH, int height = wxCHOICE_HEIGHT); int wxGetSingleChoiceIndex (const wxString & message, const wxString & caption, int n, const wxString * choices, wxWindow * parent = (wxWindow *) NULL, int x = -1, int y = -1, bool centre = TRUE, int Width = wxchoice_WIDTH, INT Height = wxchoice_HEIGHT);
WxgetsinglechoiceData
WXGetSinglechoiceData displays wxsinglechoiceDialog and returns the data associated with the selected item.
void * wxGetSingleChoiceData (const wxString & message, const wxString & caption, const wxArrayString & choices, void ** client_data, wxWindow * parent = (wxWindow *) NULL, int x = -1, int y = -1, bool centre = TRUE, int width = Wxchoice_WIDTH, INT Height = wxchoice_HEIGHT);
void * wxGetSingleChoiceData (const wxString & message, const wxString & caption, int n, const wxString * choices, void ** client_data, wxWindow * parent = (wxWindow *) NULL, int x = -1, int y = -1, bool centre = True, int width = wxchoice_WIDTH, INT Height = wxchoice_HEIGHT); note
The definition of wxchoice_width is 200, and the definition of wxchoice_HEIGHT is 150.
Chapter 5 dialog
Directory Table of Contents
WxDialog
Constructor
Programming Dialogs
SIZERS
SIZERS AND Windows
SIZERS AND Other SIZERS
SIZERS AND SPACERS
WxBoxSizer
Wxgridsizer
WXFlexGridsizer
WxStaticBoxSizer
WxnoteBooksizer
Nesting sizers
The dialog is a window that contains the title bar. This window can be moved, which can contain controls and other windows. The dialog can be modal or non-modular. The modal dialog box is locked in other windows in the program, until the dialog exits to unlock.
WxDialog
WxDialog is the base class of all dialogs. You can customize a dialog inherited from wxdialog.
Constructor constructor
wxDialog (wxWindow * parent, wxWindowId id, const wxString & title, const wxPoint & pos = wxDefaultPosition, const wxSize & size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE, const wxString & name = "dialogBox");
The pointer of the Parent parent window, uses a Null ID independent window ID when the dialog does not have a parent window. If it doesn't need to use -1. Title shows the title in the title bar. The position of the POS dialog box. The default location when using wxdefaultposition. Size window size. The default size is wxdefaultsize. Style dialog in style. Table 5.1. WxDialog style.
WxDefault_dialog_style wxsystem_menu combines WXCAPTION. WXSYSTEM_MENU is not used on the UNIX system. WXCAPTION shows the title. WXMinimize can minimize the same wxminimize_box as wxiconize. WXMaximize to maximize display. (Only for Windows) The wxmaximize_box can maximize. The wxStay_on_top dialog will appear above other windows. (Windows only) WXSystem_Menu displays a system menu. WXSIMPLE_BORDER Bless border (GTK and Windows only) wxResize_border can drag the zoom border. (The name only for UNIX) Name window. This parameter is associated with an option. This allows the user to set the MOTIF resource value for a separate window. Dialog programming
WXWindows requires a resource file when you want to use the dialog box in the program. When you don't need an additional icon, its use is as simple as you see in Example 5.1.
Example 5.1. A simple resource file.
#include "wx / msw / wx.rc"
Example 5.2 shows the definition of the information dialog box in the simple text editor earnestly developed. Example 5.3 is its implementation.
Example 5.2. AboutDialog.h - Definition of the dialog.
#ifndef _ABOUTDIALOG_H #define _ABOUTDIALOG_H class AboutDialog: public wxDialog {public: / ** * constructor * / AboutDialog (wxWindow * parent); / ** * destructor * / virtual ~ AboutDialog () {} / ** * Set The text in the dialog box. * / void settext (const wxString & text); private: wxStaticText * m_pinfotext; wxbutton * m_pokbutton;}; #ENDIF
Example 5.3. AboutDialog.cpp - Realization of Dialog
// for Compilers That Supports precompilation, include "wx / wx.h" #include "wx / wxprec.h" #1ndef wx_precomp #include "wx / wx.h" #ENDIF #include "AboutDialog.h" AboutDialog :: AboutDialog (wxwindow * parent): wxdialog (Parent, -1, "About Simple Text Editor", WXDefaultPosition, WXSIZE (200, 200), wxdefault_dialog_style) {m_pinfotext = new wxStaticText (this, -1, ", wxpoint (5, 5 ), wxsize (100, 100), wxalign_centre); m_pokbutton = new wxbutton (this, wxid_ok, "ok", wxpoint (5, 40));} void Aboutdialog :: setText (const wxstring & text) {m_pinfotext-> setLabel TEXT);
There is no event processing in the example, which is not required because all things are done by WXWindows default event processing mechanism. The dialog box is automatically exited when the user clicks the button identified by wxid_ok or wxid_cancel. Example 5.4 is the code used to display the dialog when the user clicks on the menu.
Example 5.4. Display dialog.
void TextFrame :: OnMenuInfoAbout (wxCommandEvent & event) {AboutDialog * dlg = new AboutDialog (this); dlg-> SetText ( "(c) 2001 SAW Franky Braem / nSimple Text Editor / n"); dlg-> ShowModal ();} Figure 5.1. About dialog box.
Focus
If the OK or CANCEL button code in the example is not used, the default event processing is not used. At this time, the dialog box must be called DESTROY in the EVT_CLOSE event. The program is still running when the dialog is not revoked.
SIZERS
The dialog box created in the last example may not be the user's desirable, so that the text and buttons may be more better. In addition, what will occur if the size of the text changes? How to make the button under text in the center?
WXWindows provides two ways to solve the problem of layout. Use constraints in the first version of WXWindows, starting from the second edition using SIZERS. Although constraints can still be used in the current version, SIZERS is the first choice for WXWindows for control layout. WXSIZER is all abstract base classes of SIZERS. WXSIZER cannot be used directly, you must replace it with a derived class, usual derived classes are: WXBoxsizer, WxStaticBoxsizer, WxNoteBooksizer, WxGridsizer and WXFlexGridsizer.
The layout algorithm used by SIZERS can be compared to any one of Java, GTK .... The basic principle is that each Sizer project reports the minimum size it requested, the size of the parent window changes as needed. This means that the size of the parent window cannot be specified by the developer. When the window contains a Sizer, SIZER will return a suggestive size, and Sizer will ask the recommended size of the sub-components it contains, these components can be a window, other Sizer Or blank space. The parent window automatically calculates the size according to the answer.
This allows Sizer to properly write multi-platform procedures. Consider the following questions: The font size in Unix, Motif, Windows is not exactly the same. How should you set the original size of the dialog? Solution is to let Sizer to handle this problem for you.
note
When the window has a Sizer, the layout algorithm is not automatically called. To call the Layout method containing the Sizer window before the window is displayed. You must also call Layout at the same time when the window is scaled. This can be omitted by calling setAutoLayout containing the TUE parameter.
SIZERS and windows
Void Add (wxwindow * window, int option = 0, int flag= 0, int border = 0, wxobject * userdata = null);
The Add method is used to add a window to the Sizer entry.
Void Insert (int Before, wxwindow * window, int option = 0, int flag= 0, int border = 0, wxobject * userdata = null);
INSERT is used to insert a window before Berfore.
Void Prepend (wxwindow * window, int option = 0, int flag = 0, int border = 0, wxobject * userdata = null);
Prepend is used to set a window to become the first item of an entry list. Void Remove (wxwindow * window);
Remove is used to remove a window from the list of items.
Option and WXBoxSizer have been used. 0 indicates that the entry is not allowed in the size of the SIZER main direction (the direction specified by SIZER), 1 indicates that the SIZER is mainly scaled. FLAG is used to set the flag to use the "or" operator to use it. Table 5.2. Border flag of wxsizer
Wxtop border at the top wxbottom border at the bottom WXLEFT Border on the left wxright border on the right wxall border on all. Table 5.3. WXSIZER behavior
wxGROW or wxEXPAND entry may scale the scaled entry may wxSHAPED wxALIGN_CENTER or wxALIGN_CENTRE entry in the central wxALIGN_LEFT entry Left entry wxALIGN_TOP right-aligned entry is aligned wxALIGN_RIGHT wxALIGN_CENTER_HORIZONTAL entry wxALIGN_CENTER_VERTICAL entry direction perpendicular to the central horizontal center. Border defines the width of the border. UserData allows an additional object to be attached to the Sizer entry. Can be used by derived class.
SIZERS with other Sizer
SIZERS can nested
Void Add (wxsizer * sizer, int option = 0, int flag = 0, int border = 0, wxobject * userdata = null);
The Add method is used to add a Sizer to the Sizer entry.
Void Insert (int Before, wxsizer * sizer, int option = 0, int flag= 0, int border = 0, wxobject * userdata = null);
INSERT inserts a Sizer before the entry Before.
Void Prepend (wxsizer * sizer, int option = 0, int flag = 0, int border = 0, wxobject * userdata = null);
Prepend is used to set a first item that Sizer becomes an entry list.
Void Remove (WXSIZER * SIZER);
REMOVE is used to remove a Sizer from the list of entries.
More parameter information See "SIZERS and Windows"
SIZERS and SPACER
Spacer is used to insert a blank between the controls. Allows expansion when Spacer is between two entries. The results will keep the left alignment other entries to keep the right alignment using the first entry.
Void Add (int Width, int Height, int option = 0, int flag= 0, int border = 0, wxobject * userdata = null);
The Add method is used to add a sparable to the Sizer entry.
Void Insert (int Before, int width, int = 0, int border = 0, wxObject * userdata = null); Insert Before inserting a Spacer into the Before entry.
Void Prepend (int Width, int Height, int option = 0, int flag= 0, int border = 0, wxobject * userdata = null);
Prepend Sets a Spacer's first entry for the list of items.
More parameter details See "SIZERS AND WINDOWS"
WxBoxSizer
WXBoxSizer is used to place controls or a column according to different signs. It can stretch horizontally or vertically.
Constructor constructor
WXBoxsizer (int orient);
ORIENT direction. Table 5.4. WXBOXSIZER
Wxhorizontal horizontal wxvertical vertical.
In the following example, a Sizer full of dialogs is created. Its main direction is vertical. All other sizer are the child control of this Sizer, all horizontally. They can be expanded in the horizontal direction, but the vertical direction cannot be. The second SIZER is used to lay out against the OK button, which will allow the button to keep the fixed boundary between the dialog frame. Specifies the size of the border to 20 when adding buttons.
Example 5.5. WXBOXSIZER
AboutDialog :: AboutDialog (wxWindow * parent): wxDialog (parent, -1, "About Simple Text Editor", wxDefaultPosition, wxSize (200, 200), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) {wxBoxSizer * dialogSizer = new wxBoxSizer (wxVERTICAL); wxBoxSizer * textSizer = new wxBoxSizer (wxHORIZONTAL); m_pInfoText = new wxStaticText (this, -1, "", wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER);. // The text can grow horizontally textSizer-> Add (m_pInfoText, 1, 0); wxBoxSizer * Buttonsizer = new wxboxsizer (wxhorizontal); m_pokbutton = new wxbutton (this, wxid_ok, "ok", wxpoint (-1, -1)); // the Button Can Grow Horizontally, Not VerticalL. // The Button Has A LEFT AND right border with size 20 buttonSizer-> Add (m_pOkButton, 1, wxLEFT | wxRIGHT, 20);. // The sizers can not change their vertical size They can only grow horizontally dialogSizer-> Add (textSizer, 0, wxGROW). Dialogsizer-> Add (Buttonsizer, 0, wxGrow); setsizer (Dialogsizer); setOutoLayout (TRUE); layout ();} Figure 5.2. Using WXBoxSizer about dialogs.
Wxgridsizer
Grid SIZER is a two-dimensional table layout control with the same size unit. The wide and high of each cell are the maximum width and maximum height of the control. When a grid Sizer is created, it needs to know how many rows and columns needed. If there is one of these parameters, this value is calculated by the grid Sizer. It is also necessary to specify the interval between rows and columns.
Constructor constructor
WXGridsizer (int Rows, int COLS, INT VGAP, INT HGAP); WXGridsizer (int COLS, INT VGAP = 0, INT HGAP = 0);
Rows Specifies the number of rows cols specify the interval between the column VGAP specifies the column. HGAP specifies the interval between rows.
The following example shows how to use WXGridSizer to implement the layout of the controls in the dialog box. Example will establish a spacing between the arab and a column, the interval between the rows and columns is 10.
Example 5.6. Use of WxGridsizer
AboutDialog :: AboutDialog (wxWindow * parent): wxDialog (parent, -1, "About Simple Text Editor", wxDefaultPosition, wxSize (200, 200), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) {wxGridSizer * dialogSizer = new wxGridSizer (2, 1, 10 , 10); m_pInfoText = new wxStaticText (this, -1, "", wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER); dialogSizer-> Add (m_pInfoText, 0, wxALIGN_CENTER); m_pOkButton = new wxButton (this, wxID_OK, "Ok", wxPoint (-1, -1)); Dialogsizer-> Add (m_pokbutton, 0, wxalign_center); setsizer (dialogsizer); setOutoLayout (TRUE); layout ();} wxflexgridsizer
Curve Grid Sizer is a two-dimensional table layout control, all of which has the same width in the same line and the cells in the same column have the same height.
If you need to join a label on the control in the dialog box, the grid Sizer is very useful. Figure 5.3 shows an example of proper use of WXFlexGridsizer. In the first column contains labels, the widest label determines the column width of the first column. This ensures that the control is vertical. Creating this dialog box is shown in Example 5.7. Create two lines with two columns, when adding controls to Sizer, they are placed from top to bottom.
Constructor
WXFlexGridsizer (int Rows, int COLS, INT VGAP, INT HGAP); WXFLEXGRIDSIZER (int COLS, INT VGAP = 0, INT HGAP = 0);
Parameter description See "WxGridsizer"
Figure 5.3. WXFLEXGRIDSIZER
Example 5.7. WWFlexGridsizer
wxFlexGridSizer * dialogSizer = new wxFlexGridSizer (2, 2, 10, 10); dialogSizer-> Add (new wxStaticText (this, -1, "Username"), 0, wxALIGN_CENTRE_VERTICAL); dialogSizer-> Add (new wxTextCtrl (this, ID_USER_NAME ), 0, wxALIGN_CENTRE_VERTICAL); dialogSizer-> Add (new wxStaticText (this, -1, "Password"), 0, wxALIGN_CENTRE_VERTICAL); dialogSizer-> Add (new wxTextCtrl (this, ID_PASSWORD), 0, wxALIGN_CENTRE_VERTICAL); dialogSizer- > Add (new wxStaticText (this, -1, "Retype Password"), 0, wxALIGN_CENTRE_VERTICAL); dialogSizer-> Add (new wxTextCtrl (this, ID_PASSWORD2), 0, wxALIGN_CENTRE_VERTICAL); SetSizer (dialogSizer); SetAutoLayout (TRUE); Layout (); wxStaticboXSizer
WxStaticBoxSizer inherits from wxboxsizer. It works the same as Box Sizer. But it draws a static box around Sizer.
Constructor
WXStaticBoxSizer (wxStaticBox * box, int orient);
Box is a WXStaticBox pointer. The static frame is not done by Sizer, it must be done by developers.
Orient Box Sizer, see "wxboxsizer"
WxnoteBooksizer
Wxnotebooksizer is a Sizer that is working on WXNotebook.
Sizer nested
Sizer is a nested. The next example shows a dialog box that combines WXBoxSizer and WxFlexGridSizer. Figure 5.4 shows the operation results. WXBoxSizer is used to place an OK button in the center below the other controls in the dialog.
Example 5.8. SIZER Nested
wxBoxSizer * dialogSizer = new wxBoxSizer (wxVERTICAL); wxFlexGridSizer * controlSizer = new wxFlexGridSizer (2, 2, 10, 10); controlSizer-> Add (new wxStaticText (this, -1, "Username"), 0, wxALIGN_CENTRE_VERTICAL); controlSizer -> Add (new wxTextCtrl (this, -1), 0, wxALIGN_CENTRE_VERTICAL); controlSizer-> Add (new wxStaticText (this, -1, "Password"), 0, wxALIGN_CENTRE_VERTICAL); controlSizer-> Add (new wxTextCtrl (this , -1), 0, wxalign; controlsizer-> add (new wxstatic "), 0, wxalign_centre_vertical; controlsizer-> add (new wxtextctrl (this, -1), 0, 0, wxALIGN_CENTRE_VERTICAL); wxBoxSizer * buttonSizer = new wxBoxSizer (wxVERTICAL); buttonSizer-> Add (new wxButton (this, wxID_OK, "Ok")); dialogSizer-> Add (controlSizer); dialogSizer-> Add (20, 20); dialogSizer -> Add (Buttonsizer, 0, wxalign_centre); Setsizer (Dialogsizer); setOutoLayout (TRUE); layout (); Figure 5.4.sizer nested