Search code examples
c++user-interfacewxwidgets

wxTextCtrl not aligning to center - wxSizerFlags not working in wxWidget


This code displays a single textbox and a button. When the user clicks the button, the window exits, however I want to put the textControl to the center of the window but it's not working. Here's my code:

// base.h

#ifndef base_h_
#define base_h_
#include <wx/app.h>
#include <wx/button.h>
#include <wx/string.h>
#include <wx/frame.h>
#include <wx/gdicmn.h>
#include <wx/sizer.h>
#include <wx/panel.h>

class MainApp : public wxApp {
public:
    virtual bool OnInit();
};

class MainFrame: public wxFrame {
public:
    MainFrame( const
    wxString& title, const wxPoint& pos, const wxSize& size );

    wxBoxSizer *sizer;
    void OnExit(wxCommandEvent& event);

    DECLARE_EVENT_TABLE()
};

#endif

// base.cpp
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include "base.h"

IMPLEMENT_APP(MainApp)

bool MainApp::OnInit() {
    MainFrame *MainWin = new MainFrame(_T("gui"), wxDefaultPosition, wxSize(5000, 5000));

    MainWin->Show(TRUE);
    SetTopWindow(MainWin);
    return TRUE;
}

BEGIN_EVENT_TABLE ( MainFrame, wxFrame)
EVT_BUTTON ( 3, MainFrame::OnExit )
END_EVENT_TABLE()

MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size): wxFrame((wxFrame*)NULL,- 1, title, pos, size) {

    wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
    wxPanel *panel = new wxPanel(this, wxID_ANY, wxPoint(0, 0));
    sizer->Add(new wxTextCtrl(panel , 1, ""), wxSizerFlags().Center());
    sizer->SetSizeHints(this);
    SetSizer(sizer);
}

void MainFrame::OnExit( wxCommandEvent& event) {
    Close(TRUE);
}

I don't know what I'm doing wrong here, shouldn't wxSizerFlags().Center do exactly what I want?


Solution

  • Your text control is wrapped inside a wxPanel. You add the text control to the sizer and set the sizer to the frame. This won't work and may even cause errors. You need to create two sizers, one for the panel and one for the frame. You have several options: You can have the panel expand to the size of the frame and have the text ctrl placed in the center of the panel, or you can center the panel and have the text ctrl expand to the size of the panel. Here's some code for the first option:

    wxPanel* panel = new wxPanel(this, wxID_ANY);
    wxTextCtrl* text = new wxTextCtrl(panel, 1, "");
    
    wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL);
    panelSizer->Add(text, wxSizerFlags().Center());
    panel->SetSizer(panelSizer);
    
    wxBoxSizer* frameSizer = new wxBoxSizer(wxVERTICAL);
    frameSizer->Add(panel, wxSizerFlags().Expand());
    SetSizer(frameSizer);
    

    Note that I'm not familiar with wxSizerFlags, but I suppose that it should work like this. You may also have to set a size for the panel explicitly - right now it will use some default size.