Search code examples
c++wxwidgets

Writing end of line to wxTextCtrl


I was trying to write text to a wxTextctrl object in a wxWidgets application. Example code is below. For some reason, I'm not managing to get a line break. And most examples I've found online did one of the things that aren't working here.

What I'm getting

The code:

#include "wx/wx.h"

using namespace std;

class MainWindow : public wxFrame {
 public:
  MainWindow(const wxString& title);
  wxTextCtrl* textctrl;
};

class MyApp : public wxApp {
 public:
  virtual bool OnInit();
  MainWindow* main_window;
};

MainWindow::MainWindow(const wxString& title)
    : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(280, 180)) {
  // Add text window:
  textctrl =
      new wxTextCtrl(this, -1, wxT(""), wxPoint(-1, -1), wxSize(250, 150));

  // This writes to the middle of the text white space, but does not understand
  // endl \n or \r\n
  ostream log_stream(textctrl);
  log_stream << "Hey Joe! \n";
  log_stream << "Buckle up!\r\n";
  log_stream << "Lorem ipsum dolor sit amet" << endl;

  wxStreamToTextRedirector redirect(textctrl);
  cout << "Not yet " << endl;
  cout << "One more \n";
  cout << "Just one more \r\n";

  cout << "Fine, I quit.";

  Centre();
}

Also, the text is not breaking automatically due to the window size.


Solution

  • You need to create wxTextCtrl with wxTE_MULTILINE style. You then normally only need \n which will be correctly interpreted for each platform.