Tag Archive : wxWidgets

/ wxWidgets

First wxWidget Program

December 9, 2015 | Article | No Comments

After learning some wxWidgets basic, lets open new article for discussing a simple application.

In this article we will cover a basic in creating a wxWidget frame and show how to display an icon. Next we will create a simple example demonstrating usage of an event. Finally, we will see, how widgets communicate in wxWidgets applications.

A simple application

First we create the very basic wxWidgets program.

/** filename: simple.h **/
#include <wx/wx.h>

class Simple : public wxFrame
{
public:
    Simple(const wxString& title);
};

That’s for class declaration, this one for the implementation.

/** filename: simple.cpp **/
#include "simple.h"

Simple::Simple(const wxString& title)
       : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(250, 150))
{
  Centre();
}

And then the main. First the declaration and then the implementation

/** filename: main.h **/
#include <wx/wx.h>

class MyApp : public wxApp
{
  public:
    virtual bool OnInit();
};
/** filename: main.cpp **/
#include "main.h"
#include "simple.h"

IMPLEMENT_APP(MyApp)

bool MyApp::OnInit()
{
    Simple *simple = new Simple(wxT("Simple"));
    simple->Show(true);
    SetTopWindow(simple);

    return true;
}

Compile the above code as discussed before.

 

Getting Started with wxWidgets

December 9, 2015 | Article | No Comments

People who are completely new to wxWidgets would normally follow the steps illustrated below.

WxGettingStartedRoadmap

In this article we will set our environment for developing a wxWidget application.

Installing wxWidgets and Setting up IDE

When developing application using wxWidget, we can choose whether use helping from IDE or not. For an overview of IDEs that have been reported to work with wxWidgets, you can see the list of IDEs on wxWidgets site.

We won’t cover installation of any IDE in this section, but I would recommend you to install one.

Your main guide for compiling wxWidgets should be the installation instructions : Look in <code-base-dir>/docs/.

On Windows

<to be continued>

On Linux

Getting Started

Before getting started, make sure you have installed all necessary build tools, including g++ and autotools. You will also need gtk+ library.

It is recommended to use at least GTK+ 2.2.3, and some features are only available when using more recent version, like GTK+ 2.8.

Building and Installation

Download the wxWidget source archive from http://www.wxwidgets.org/downloads/. The latest development is recommended, and when writing this article, the latest version is version 2.9.4.

You will need to call configure to configure the compilation setting. It is also recommended to enable unicode support for wxWidgets.

./configure --enable-unicode

However, if you want to compile wxWidgets on a 64-bit version of Linux in such a way that the library can be linked to both statically and dynamically, then you want to add the -fPIC flag to the configure call. That is done in the following way:

./configure --enable-unicode CFLAGS="-fPIC" CXXFLAGS="-fPIC"

The options you pass to configure at this point will determine what build you get.

–enable-unicode makes a Unicode build
–with-opengl enables OpenGL support
–disable-shared builds static libs instead of shared ones
–prefix=[…] makes wxWidgets be installed in another location than default /usr/local

A list of all possible options can be seen using ./configure –help command.

If it stops saying it can’t find a package, install it (with -dev packages if any) and run configure again. When it is done without errors, you are ready to build. When the build is done, and if no error occured, you can now install it. You also need root privileges to install it.

make
make install

Enter your password as needed. wxWidgets will be installed in /usr/local/

On some systems it is also necesary to run sudo ldconfig at this point.

Compile an Application

The tool wx-config allows you to quickly build wxWidgets apps

g++ `wx-config --cppflags` `wx-config --libs` widgetTest.cpp

wx-config –cppflags returns flags necessary to compilation, wx-config –libs returns flags necessary to linking. This little example has a single file so both are used at the same time but in a bigger project compiling and linking will most likely be two different steps. (How to use g++ is beyond the scope of this document)

For more information, see article Wx-Config.

On Mac OS

<to be continued>

wxWidget Helper Classes

December 9, 2015 | Article | 1 Comment

wxWidgets consists of a large group of helper classes, that help programmers to do their job. These include classes for working with strings, files, XML files, streams, database or network.

In this article, we will discuss about some helper classes that frequently used or useful for developing with wxWidget later. We will also illustrate some of the helper classes in simple console-based applications (although we can also use GUI applications).

Console

This is a simple console application. The application puts some text into the console window.

/** filename: console.cpp **/
#include <wx/string.h>

int main(int argc, char **argv) {
  wxPuts(wxT("A wxWidgets console application"));
}

You should get output, a string “A wxWidgets console application” on your terminal.

wxString

wxString is a class representing a character string.

In the following example, we define three wxStrings instances. We create one string of these strings using addition operation. Create a file addition.cpp and write these into it:

/** filename: addition.cpp **/
#include<wx/string.h>

int main(int argc, char **argv) {
  wxString str1 = wxT("Linux");
  wxString str2 = wxT("Operating");
  wxString str3 = wxT("System");

  wxString str = str1 + wxT(" ") + str2 + wxT(" ") + str3;
  wxPuts(str);
}

It should give you “Linux Operating System” as the output.

A method printf() of wxString can also be used for formatting the strings.
/** filename: printf.cpp **/
#include <wx/string.h>

int main(int argc, char **argv)
{

  int flowers = 21;

  wxString str;
  str.Printf(wxT("There are %d red roses."), flowers);

  wxPuts(str);
}

The following example checks, whether a string contains another string. For this we have a Contains() method.

/** filename: contains.cpp **/
#include <wx/string.h>

int main(int argc, char **argv)
{

  wxString str = wxT("The history of my life");

  if (str.Contains(wxT("history"))) {
      wxPuts(wxT("Contains!"));
  }

  if (!str.Contains(wxT("plain"))) {
      wxPuts(wxT("Does not contain!"));
  }
}

A wxString always has length and this length can be obtained by method Len(). It will return the number of characters on string.

#include <wx/string.h>

int main(int argc, char **argv)
{
  wxString str = wxT("The history of my life");
  wxPrintf(wxT("The string has %ld characters\n"), str.Len());
}

The MakeLower() and MakeUpper() methods can be used to make characters lower case and upper case.

#include <wx/string.h>

int main(int argc, char **argv)
{
  wxString str = wxT("The history of my life");

  wxPuts(str.MakeLower());
  wxPuts(str.MakeUpper());
}

Also note that, when the MakeLower() or MakeUpper() used, the effect will remain.

Utility functions

wxWidgets has several handy utility functions for executing a process, getting a home user directory or getting the OS name.

In the following example, we execute the ls command. For this, we have the wxShell() function. This methods is only for for Unix.

#include <wx/string.h>
#include <wx/utils.h>

int main(int argc, char **argv)
{
  wxShell(wxT("ls -l"));
}

Another thing we can do are getting the home user directory, os name, user name, host name and total free memory.

#include <wx/string.h>
#include <wx/utils.h>

int main(int argc, char **argv)
{
  wxPuts(wxGetHomeDir());
  wxPuts(wxGetOsDescription());
  wxPuts(wxGetUserName());
  wxPuts(wxGetFullHostName());

  long mem = wxGetFreeMemory().ToLong();

  wxPrintf(wxT("Memory: %ld\n"), mem);
}

It looks like wxWidget is optimized for lsb based linux distribution. wxWidget on my Slackware64, which is not using LSB, gives some expected result.

Time & date

wxWidget also offer utilities for working with date & time. The example shows current date or time in various formats.

#include <wx/datetime.h>

int main(int argc, char **argv)
{
  wxDateTime now = wxDateTime::Now();

  wxString date1 = now.Format();
  wxString date2 = now.Format(wxT("%X"));
  wxString date3 = now.Format(wxT("%x"));

  wxPuts(date1);
  wxPuts(date2);
  wxPuts(date3);
}

Next we will show current time in different cities.

#include <wx/datetime.h>

int main(int argc, char **argv)
{
  wxDateTime now = wxDateTime::Now();

  wxPrintf(wxT("  Jakarta: %s\n"), now.Format(wxT("%a %T"),
      wxDateTime::GMT7).c_str());
  wxPrintf(wxT("  Moscow: %s\n"), now.Format(wxT("%a %T"),
      wxDateTime::MSD).c_str());
  wxPrintf(wxT("Budapest: %s\n"), now.Format(wxT("%a %T"),
      wxDateTime::CEST).c_str());
  wxPrintf(wxT("  London: %s\n"), now.Format(wxT("%a %T"),
      wxDateTime::WEST).c_str());
  wxPrintf(wxT("New York: %s\n"), now.Format(wxT("%a %T"),
      wxDateTime::EDT).c_str());
}

The following example shows, how we can add date spans to our date/time. We add one month to the current time.

#include <wx/datetime.h>

int main(int argc, char **argv)
{
  wxDateTime now = wxDateTime::Now();
  wxString date1 = now.Format(wxT("%B %d %Y"));
  wxPuts(date1);

  wxDateSpan span(0, 1); // 0 year, 1 month
  wxDateTime then = now.Add(span);

  wxString date2 = then.Format(wxT("%B %d %Y"));
  wxPuts(date2);

}

Files

wxWidgets has several classes to facilitate working with files. wxWidgets use low level access to files, as opposed to working with streams.

In the following example, we use the wxFile class to create a new file and write data to it. We also test, whether the file is opened. Note, that when we create a file, it automatically stays as opened.

#include <wx/file.h>

int main(int argc, char **argv)
{
  wxString str = wxT("You make me want to be a better man.\n");

  wxFile file;
  file.Create(wxT("quote"), true);

  if (file.IsOpened())
      wxPuts(wxT("the file is opened"));

  file.Write(str);
  file.Close();

  if (!file.IsOpened())
      wxPuts(wxT("the file is not opened"));
}

The wxTextFile is a simple class which allows to work with text files on line by line basis. It is easier to work with this class than with wxFile class.In the next example, we will print the number of lines in a file, first and last lines and finally we will read and show the contents of the file.

#include <wx/textfile.h>

int main(int argc, char **argv)
{
  wxTextFile file(wxT("test.c"));

  file.Open();

  wxPrintf(wxT("Number of lines: %d\n"), file.GetLineCount());
  wxPrintf(wxT("First line: %s\n"), file.GetFirstLine().c_str());
  wxPrintf(wxT("Last line: %s\n"), file.GetLastLine().c_str());

  wxPuts(wxT("-------------------------------------"));

  wxString s;

  for ( s = file.GetFirstLine(); !file.Eof();
      s = file.GetNextLine() )
  {
       wxPuts(s);
  }

  file.Close();
}

The wxDir class allows us to enumerate files and directories.

In the following example, we will print all files and directories available in the current working directory.

#include <wx/dir.h>
#include <wx/filefn.h>

int main(int argc, char **argv)
{
  wxDir dir(wxGetCwd());

  wxString file;

  bool cont = dir.GetFirst(&file, wxEmptyString,
      wxDIR_FILES | wxDIR_DIRS);

  while (cont) {
      wxPuts(file);
      cont = dir.GetNext(&file);
  }
}

Introduction to wxWidgets Toolkit

December 9, 2015 | Article | 2 Comments

In beginning it is known as wxWindows.

wxWidgets is a GUI (Graphical User Interface) toolkit and library for creating C++ applications. It is an open source, mature and cross-platform toolkit. wxWidgets applications run on all major OS platforms, Windows, Unix and Mac. The project was started by Julian Smart in 1992. wxWidgets is much more than a toolkit. It provides a large variety of classes for handling streams, databases, threads, online help or application settings. wxWidgets consists of a large group of widgets.

Official site of wxWidget is http://www.wxwidgets.org/

To use tutorial in this site, you should have wxWidget installed. I use wxWidget 2.9.4 mainly and can be downloaded from here http://www.wxwidgets.org/downloads/.

wxWidgets gives you a single, easy-to-use API for writing GUI applications on multiple platforms. Link it with the appropriate library for your platform (Windows/Unix/Mac) and compiler (almost any popular C++ compiler), and your application will adopt the look and feel appropriate to that platform. On top of the great GUI functionality, wxWindows gives you: online help, network programming, streams, clipboard and drag and drop, multithreading, image loading and saving in a variety of popular formats, database support, HTML viewing and printing, and much more.

Who Should Use wxWidgets?

wxWidgets is a framework very much similar to MFC, except for a few negative points of its own. Those MFC programmers who are aware of the growing number of Linux users and who want to write cross platform GUI applications can use wxWidgets. With wxWidgets, it is very easy to use a framework based on C++ and it has a proven record of 13 years. In fact, wxWidgets is very stable and is supported on:

  • Windows 3.1, Windows 95/98, Windows NT, Windows 2000/XP, Windows ME, Windows CE.
  • Linux and other UNIX platforms with GTK+.
  • UNIX with Motif or the free Motif clone Lesstif.
  • Mac OS.
  • Embedded platforms are being investigated. See the wxUniversal project.
  • An OS/2 port is in progress, and you can also compile wxWidgets for GTK+ or Motif on OS/2.

The C++ programming language

The C++ programming language is one of the most widely used programming languages. It is used in many famous desktop applications like MS Office, Macromedia Flash, Firefox, Photoshop or 3D Max. C++ dominates also the world of PC games. It is one of the most difficult programming languages. On the other hand, programming in C++ today is different from programming 10 years ago. There are many tools and libraries that make the programming easier.

For tutorials on C++ programming languages, you can visit here.

Why wxWidgets?

There are a number of options available for writing cross platform GUI development, like: JAVA, Mono.NET, Qt, etc. Java has failed to prove itself as an efficient alternative. Qt is good but commercial and nobody knows its future. Mono.NET seems to be good but is largely driven by Microsoft, it seems like a copy of the work done by Microsoft and it has not yet proved itself as a successful alternative. Also, people would not like to use an extra burden of layer for highly efficient software. As wxWidgets does not use any middle layer and uses only the native controls available on the platform, it gives a nice look and feel to the application.

  • It is very complete. There are many utility classes like : wxRegEx, wxFTP, wxSplashScreen, wxZipInputStream, etc.
  • It is still heavily developed, and has a lot of support from the open source community.
  • Many compilers and platforms are supported : Windows, Linux, Mac, Unix.
  • There’s a lot of documentation available on the internet, forums, wxBook.
  • It’s free for personal and commercial use, and is more flexible than the LGPL license.
  • Whenever possible, wxWindows uses the platform SDK. This means that a program compiled on Windows will have the look and feel of a Windows program, and when compiled on a Linux machine, it will have the look and feel of a Linux program.
  • Ease of learning, it has the same Event tables and similar API and classes like that of WINAPI and MFC.
  • A lot of sample is provided in the samples directory of the installation, which contains how to use the basic controls, multi threading, MDI, drag and drop, sockets, printing and lots more.
  • A lot of ready to use classes are available, like: wxGenericDirCtrl, wxCalendarCtrl, wxDatePickerCtrl, wxTipWindow, wxStyledTextCtrl, wxStaticPicture, wxLEDNumberCtrl, wxEditableListBox, wxFoldPanelBar, wxGIFAnimationCtrl, wxSplashScreen, OGL (Object Graphics Library), FL (Frame Layout), etc. This is one of the main repository.
  • A lot of add on libraries are available to make the programming task more easier:

Main Features

  • Multi threading.
  • Clipboard and drag and drop.
  • Network programming, like: wxSMTP, wxHTTP, wxFTP.
  • Image loading and saving in a variety of popular formats.
  • Streams (ZIP, Network, File, etc.), like: wxRarInputStream.
  • Database support, like: wxDao.
  • HTML viewing and printing, like: wxMozilla, wxIE.
  • XML based resource, multi language/Unicode support.
  • Default style themes available with the OS (e.g.: XP style themes).

Comparison to MFC

MFC and wxWidgets macros

MFC version wxWidgets version
BEGIN_MESSAGE_MAP BEGIN_EVENT_TABLE
END_MESSAGE_MAP END_EVENT_TABLE
DECLARE_DYNAMIC DECLARE_CLASS
DECLARE_DYNCREATE DECLARE_DYMAMIC_CLASS
IMPLEMENT_DYNAMIC IMPLEMENT_CLASS
IMPLEMENT_DYNCREATE IMPLEMENT_DYNAMIC_CLASS
IsKindOf(RUNTIME_CLASS(CWindow)) IsKindOf(CLASSINFO(wxWindow))

MFC and wxWidgets classes

Miscellaneous Classes
MFC version wxWidgets version
CWinApp wxApp
CObject wxObject
CCmdTarget wxEvtHandler
CCommandLineInfo wxCmdLineParser
CMenu wxMenu, wMenuBar, wxMenuItem
CWaitCursor wxBusyCursor
CDataExchange wxValidator
Window Classes
MFC version wxWidgets version
CFrameWnd wxFrame
CMDIFrameWnd wxMDIParentFrame
CMDIChildWnd wxMDIChildFrame
CSplitterWnd wxSplitterWindow
CToolBar wxToolBar
CStatusBar wxStatusBar
CReBar wxCoolBar, but see contrib/src/fl and wxAUI, wxDockIt
CPropertyPage wxPanel
CPropertySheet wxNotebook, wxPropertySheetDialog
Dialog Classes
MFC version wxWidgets version
CDialog wxDialog
CColorDialog wxColourDialog
CFileDialog wxFileDialog
CFindReplaceDialog wxFindReplaceDialog
CFontDialog wxFontDialog
CPageSetupDialog wxPageSetupDialog
CPrintDialog wxPrintDialog
Control Classes
MFC version wxWidgets version
CAnimateCtrl wxMediaCtrl, wxAnimationCtrl
CButton wxButton
CBitmapButton wxBitmapButton
CComboBox wxComboBox, wxChoice
CDateTimeCtrl wxDatePickerCtrl
CEdit wxTextCtrl
CHotKeyCtrl None, but see Keybinder
CListBox, CDragListBox wxListBox
CCheckListBox wxCheckListBox
CListCtrl wxListCtrl, wxListView
CMonthCalCtrl wxCalendarCtrl
CProgressCtrl wxGauge
CReBarCtrl None, but see contrib/src/fl and wxAUI, wxDockIt
CRichEditCtrl wxTextCtrl
CScrollBar wxScrollBar
CSliderCtrl wxSlider
CSpinButtonCtrl wxSpinButton, wxSpinCtrl
CStatic wxStaticText, wxStaticLine, wxStaticBox, wxStaticBitmap
CStatusBarCtrl wxStatusBar
CTabCtrl wxTabCtrl
CToolBarCtrl wxToolBar
CToolTipCtrl wxToolTip
CTreeCtrl wxTreeCtrl
Graphics Classes
MFC version wxWidgets version
CBitmap wxBitmap, wxImage, wxIcon, wxCursor
CBrush wxBrush
CPen wxPen
CFont wxFont
CImageList wxImageList, wxIconBundle
CPalette wxPalette
CRgn wxRegion
CClientDC wxClientDC
CMetaFileDC wxMetaFileDC
CPaintDC wxPaintDC
CWindowDC wxWindowDC
CDC wxDC, wxMemoryDC
Data Structure Classes
MFC version wxWidgets version
CArray, CObArray, CPtrArray wxArray
CStringArray wxArrayString
CDWordArray, CByteArray, CUIntArray wxArrayInt
CList, CPtrList, CObList wxList
CStringList wxArrayString, wxStringList
CMap wxHashMap
CString wxString
CPoint wxPoint
CRect wxRect
CSize wxSize
CTime wxDateTime
CTimeSpan wxTimeSpan, wxDateSpan
COleVariant wxVariant
Internet Classes
MFC version wxWidgets version
CSocket wxSocket
CFtpConnection wxFTP
CHttpConnection wxHTTP
Document/View Classes
MFC version wxWidgets version
CDocument wxDocument
CView wxView
CDocTemplate, CSingleDocTemplate, CMultiDocTemplate wxDocTemplate
Drag and Drop Classes
MFC version wxWidgets version
COleDataSource wxDataObject
COleDropSource wxDropSource
COleDropTarget wxDropTarget
File Classes
MFC version wxWidgets version
CFile wxFile, wxFFile, wxTextFile
CMemFile wxMemoryInputStream, wxMemoryOutputStream
CSocketFile wxSocketInputStream, wxSocketOutputStream
CRecentFileList wxFileHistory
Multithreading Classes
MFC version wxWidgets version
CWinThread wxThread
CCriticalSection wxCriticalSection
CMutex wxMutex
CSemaphore wxSemaphore

Class Hierarchy

A complete hierarchy for library can be sen here.

wxposter

Requirements

Convinced to use wxWidgets?

wxWidgets is cross platform library and currently available on Windows, UNIX, and Mac OS. To make use of wxWidgets, you currently need one of the following setups.

(a) for MS-Windows:

  • A 32-bit or 64-bit PC running MS Windows.
  • A Windows compiler: MS Visual C++ (embedded Visual C++ for wxWinCE port), Borland C++, Watcom C++, Cygwin, MinGW, Digital Mars C++. See install.txt for details about compiler version supported.

(b) for Unix:

  • Almost any C++ compiler, including GNU C++ and many Unix vendors compilers such as Sun CC, HP-UX aCC or SGI mipsPro.
  • Almost any Unix workstation, and one of: GTK+ 2.6 or higher (GTK+ 1.2.10 may still be supported but wxGTK1 port is not maintained any longer and lacks many features of wxGTK2; GTK+ 3 is supported but is still experimental), Motif 1.2 or higher or Lesstif. If using the wxX11 port, no such widget set is required.

(c) for Mac OS/Mac OS X:

  • A PowerPC or Intel Mac running Mac OS X 10.4 or higher
  • The Apple Developer Tools (eg. GNU C++)

Social media & sharing icons powered by UltimatelySocial