Contents Up Previous Next

wxTextCtrl

A text control allows text to be displayed and edited. It may be single line or multi-line.

Derived from

streambuf
wxControl
wxWindow
wxEvtHandler
wxObject

Include files

<wx/textctrl.h>

Window styles

wxTE_PROCESS_ENTER The control will generate the event wxEVT_COMMAND_TEXT_ENTER (otherwise pressing Enter key is either processed internally by the control or used for navigation between dialog controls).
wxTE_PROCESS_TAB The control will receive wxEVT_CHAR events for TAB pressed - normally, TAB is used for passing to the next control in a dialog instead. For the control created with this style, you can still use Ctrl-Enter to pass to the next control from the keyboard.
wxTE_MULTILINE The text control allows multiple lines.
wxTE_PASSWORD The text will be echoed as asterisks.
wxTE_READONLY The text will not be user-editable.
wxTE_RICH Use rich text control under Win32, this allows to have more than 64KB of text in the control even under Win9x. This style is ignored under other platforms.
wxTE_RICH2 Use rich text control version 2.0 or 3.0 under Win32, this style is ignored under other platforms
wxTE_AUTO_URL Highlight the URLs and generate the wxTextUrlEvents when mouse events occur over them. This style is only supported for wxTE_RICH Win32 and multi-line wxGTK2 text controls.
wxTE_NOHIDESEL By default, the Windows text control doesn't show the selection when it doesn't have focus - use this style to force it to always show it. It doesn't do anything under other platforms.
wxHSCROLL A horizontal scrollbar will be created and used, so that text won't be wrapped. No effect under wxGTK1.
wxTE_LEFT The text in the control will be left-justified (default).
wxTE_CENTRE The text in the control will be centered (currently wxMSW and wxGTK2 only).
wxTE_RIGHT The text in the control will be right-justified (currently wxMSW and wxGTK2 only).
wxTE_DONTWRAP Same as wxHSCROLL style: don't wrap at all, show horizontal scrollbar instead.
wxTE_CHARWRAP Wrap the lines too long to be shown entirely at any position (wxUniv and wxGTK2 only).
wxTE_WORDWRAP Wrap the lines too long to be shown entirely at word boundaries (wxUniv and wxGTK2 only).
wxTE_BESTWRAP Wrap the lines at word boundaries or at any other character if there are words longer than the window width (this is the default).
wxTE_CAPITALIZE On PocketPC and Smartphone, causes the first letter to be capitalized.

See also window styles overview and wxTextCtrl::wxTextCtrl.

Note that alignment styles (wxTE_LEFT, wxTE_CENTRE and wxTE_RIGHT) can be changed dynamically after control creation on wxMSW and wxGTK. wxTE_READONLY, wxTE_PASSWORD and wrapping styles can be dynamically changed under wxGTK but not wxMSW. The other styles can be only set during control creation.

wxTextCtrl text format

The multiline text controls always store the text as a sequence of lines separated by \n characters, i.e. in the Unix text format even on non-Unix platforms. This allows the user code to ignore the differences between the platforms but at a price: the indices in the control such as those returned by GetInsertionPoint or GetSelection can not be used as indices into the string returned by GetValue as they're going to be slightly off for platforms using \r\n as separator (as Windows does), for example.

Instead, if you need to obtain a substring between the 2 indices obtained from the control with the help of the functions mentioned above, you should use GetRange. And the indices themselves can only be passed to other methods, for example SetInsertionPoint or SetSelection.

To summarize: never use the indices returned by (multiline) wxTextCtrl as indices into the string it contains, but only as arguments to be passed back to the other wxTextCtrl methods.

wxTextCtrl styles

Multi-line text controls support the styles, i.e. provide a possibility to set colours and font for individual characters in it (note that under Windows wxTE_RICH style is required for style support). To use the styles you can either call SetDefaultStyle before inserting the text or call SetStyle later to change the style of the text already in the control (the first solution is much more efficient).

In either case, if the style doesn't specify some of the attributes (for example you only want to set the text colour but without changing the font nor the text background), the values of the default style will be used for them. If there is no default style, the attributes of the text control itself are used.

So the following code correctly describes what it does: the second call to SetDefaultStyle doesn't change the text foreground colour (which stays red) while the last one doesn't change the background colour (which stays grey):

    text->SetDefaultStyle(wxTextAttr(*wxRED));
    text->AppendText("Red text\n");
    text->SetDefaultStyle(wxTextAttr(wxNullColour, *wxLIGHT_GREY));
    text->AppendText("Red on grey text\n");
    text->SetDefaultStyle(wxTextAttr(*wxBLUE);
    text->AppendText("Blue on grey text\n");
wxTextCtrl and C++ streams

This class multiply-inherits from streambuf where compilers allow, allowing code such as the following:

  wxTextCtrl *control = new wxTextCtrl(...);

  ostream stream(control)

  stream << 123.456 << " some text\n";
  stream.flush();
If your compiler does not support derivation from streambuf and gives a compile error, define the symbol NO_TEXT_WINDOW_STREAM in the wxTextCtrl header file.

Note that independently of this setting you can always use wxTextCtrl itself in a stream-like manner:

  wxTextCtrl *control = new wxTextCtrl(...);

  *control << 123.456 << " some text\n";
always works. However the possibility to create an ostream associated with wxTextCtrl may be useful if you need to redirect the output of a function taking an ostream as parameter to a text control.

Another commonly requested need is to redirect std::cout to the text control. This could be done in the following way:

  #include <iostream>

  wxTextCtrl *control = new wxTextCtrl(...);

  std::streambuf *sbOld = std::cout.rdbuf();
  std::cout.rdbuf(*control);

  // use cout as usual, the output appears in the text control
  ...

  std::cout.rdbuf(sbOld);
But wxWidgets provides a convenient class to make it even simpler so instead you may just do

  #include <iostream>

  wxTextCtrl *control = new wxTextCtrl(...);

  wxStreamToTextRedirector redirect(control);

  // all output to cout goes into the text control until the exit from current
  // scope
See wxStreamToTextRedirector for more details.

Constants

The values below are the possible return codes of the HitTest method:

// the point asked is ...
enum wxTextCtrlHitTestResult
{
    wxTE_HT_UNKNOWN = -2,   // this means HitTest() is simply not implemented
    wxTE_HT_BEFORE,         // either to the left or upper
    wxTE_HT_ON_TEXT,        // directly on
    wxTE_HT_BELOW,          // below [the last line]
    wxTE_HT_BEYOND          // after [the end of line]
};
// ... the character returned

Event handling

The following commands are processed by default event handlers in wxTextCtrl: wxID_CUT, wxID_COPY, wxID_PASTE, wxID_UNDO, wxID_REDO. The associated UI update events are also processed automatically, when the control has the focus.

To process input from a text control, use these event handler macros to direct input to member functions that take a wxCommandEvent argument.

EVT_TEXT(id, func) Respond to a wxEVT_COMMAND_TEXT_UPDATED event, generated when the text changes. Notice that this event will be sent when the text controls contents changes - whether this is due to user input or comes from the program itself (for example, if SetValue() is called); see ChangeValue() for a function which does not send this event.
EVT_TEXT_ENTER(id, func) Respond to a wxEVT_COMMAND_TEXT_ENTER event, generated when enter is pressed in a text control (which must have wxTE_PROCESS_ENTER style for this event to be generated).
EVT_TEXT_URL(id, func) A mouse event occurred over an URL in the text control (wxMSW and wxGTK2 only)
EVT_TEXT_MAXLEN(id, func) User tried to enter more text into the control than the limit set by SetMaxLength.
Members

wxTextCtrl::wxTextCtrl
wxTextCtrl::~wxTextCtrl
wxTextCtrl::AppendText
wxTextCtrl::CanCopy
wxTextCtrl::CanCut
wxTextCtrl::CanPaste
wxTextCtrl::CanRedo
wxTextCtrl::CanUndo
wxTextCtrl::Clear
wxTextCtrl::Copy
wxTextCtrl::Create
wxTextCtrl::Cut
wxTextCtrl::DiscardEdits
wxTextCtrl::EmulateKeyPress
wxTextCtrl::GetDefaultStyle
wxTextCtrl::GetInsertionPoint
wxTextCtrl::GetLastPosition
wxTextCtrl::GetLineLength
wxTextCtrl::GetLineText
wxTextCtrl::GetNumberOfLines
wxTextCtrl::GetRange
wxTextCtrl::GetSelection
wxTextCtrl::GetStringSelection
wxTextCtrl::GetStyle
wxTextCtrl::GetValue
wxTextCtrl::HitTest
wxTextCtrl::IsEditable
wxTextCtrl::IsEmpty
wxTextCtrl::IsModified
wxTextCtrl::IsMultiLine
wxTextCtrl::IsSingleLine
wxTextCtrl::LoadFile
wxTextCtrl::MarkDirty
wxTextCtrl::OnDropFiles
wxTextCtrl::Paste
wxTextCtrl::PositionToXY
wxTextCtrl::Redo
wxTextCtrl::Remove
wxTextCtrl::Replace
wxTextCtrl::SaveFile
wxTextCtrl::SetDefaultStyle
wxTextCtrl::SetEditable
wxTextCtrl::SetInsertionPoint
wxTextCtrl::SetInsertionPointEnd
wxTextCtrl::SetMaxLength
wxTextCtrl::SetModified
wxTextCtrl::SetSelection
wxTextCtrl::SetStyle
wxTextCtrl::SetValue
wxTextCtrl::ChangeValue
wxTextCtrl::ShowPosition
wxTextCtrl::Undo
wxTextCtrl::WriteText
wxTextCtrl::XYToPosition
wxTextCtrl::operator <<


wxTextCtrl::wxTextCtrl

wxTextCtrl()

Default constructor.

wxTextCtrl(wxWindow* parent, wxWindowID id, const wxString& value = "", const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxTextCtrlNameStr)

Constructor, creating and showing a text control.

Parameters

parent

id

value

pos

size

style

validator

name

Remarks

The horizontal scrollbar (wxHSCROLL style flag) will only be created for multi-line text controls. Without a horizontal scrollbar, text lines that don't fit in the control's size will be wrapped (but no newline character is inserted). Single line controls don't have a horizontal scrollbar, the text is automatically scrolled so that the insertion point is always visible.

See also

wxTextCtrl::Create, wxValidator


wxTextCtrl::~wxTextCtrl

~wxTextCtrl()

Destructor, destroying the text control.


wxTextCtrl::AppendText

void AppendText(const wxString& text)

Appends the text to the end of the text control.

Parameters

text

Remarks

After the text is appended, the insertion point will be at the end of the text control. If this behaviour is not desired, the programmer should use GetInsertionPoint and SetInsertionPoint.

See also

wxTextCtrl::WriteText


wxTextCtrl::CanCopy

virtual bool CanCopy()

Returns true if the selection can be copied to the clipboard.


wxTextCtrl::CanCut

virtual bool CanCut()

Returns true if the selection can be cut to the clipboard.


wxTextCtrl::CanPaste

virtual bool CanPaste()

Returns true if the contents of the clipboard can be pasted into the text control. On some platforms (Motif, GTK) this is an approximation and returns true if the control is editable, false otherwise.


wxTextCtrl::CanRedo

virtual bool CanRedo()

Returns true if there is a redo facility available and the last operation can be redone.


wxTextCtrl::CanUndo

virtual bool CanUndo()

Returns true if there is an undo facility available and the last operation can be undone.


wxTextCtrl::Clear

virtual void Clear()

Clears the text in the control.

Note that this function will generate a wxEVT_COMMAND_TEXT_UPDATED event.


wxTextCtrl::Copy

virtual void Copy()

Copies the selected text to the clipboard under Motif and MS Windows.


wxTextCtrl::Create

bool Create(wxWindow* parent, wxWindowID id, const wxString& value = "", const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxTextCtrlNameStr)

Creates the text control for two-step construction. Derived classes should call or replace this function. See wxTextCtrl::wxTextCtrl for further details.


wxTextCtrl::Cut

virtual void Cut()

Copies the selected text to the clipboard and removes the selection.


wxTextCtrl::DiscardEdits

void DiscardEdits()

Resets the internal 'modified' flag as if the current edits had been saved.


wxTextCtrl::EmulateKeyPress

bool EmulateKeyPress(const wxKeyEvent& event)

This functions inserts into the control the character which would have been inserted if the given key event had occurred in the text control. The event object should be the same as the one passed to EVT_KEY_DOWN handler previously by wxWidgets.

Please note that this function doesn't currently work correctly for all keys under any platform but MSW.

Return value

true if the event resulted in a change to the control, false otherwise.


wxTextCtrl::GetDefaultStyle

const wxTextAttr& GetDefaultStyle() const

Returns the style currently used for the new text.

See also

SetDefaultStyle


wxTextCtrl::GetInsertionPoint

virtual long GetInsertionPoint() const

Returns the insertion point. This is defined as the zero based index of the character position to the right of the insertion point. For example, if the insertion point is at the end of the text control, it is equal to both GetValue().Length() and GetLastPosition().

The following code snippet safely returns the character at the insertion point or the zero character if the point is at the end of the control.

  char GetCurrentChar(wxTextCtrl *tc) {
    if (tc->GetInsertionPoint() == tc->GetLastPosition())
      return '\0';
    return tc->GetValue[tc->GetInsertionPoint()];
  }

wxTextCtrl::GetLastPosition

virtual wxTextPos GetLastPosition() const

Returns the zero based index of the last position in the text control, which is equal to the number of characters in the control.


wxTextCtrl::GetLineLength

int GetLineLength(long lineNo) const

Gets the length of the specified line, not including any trailing newline character(s).

Parameters

lineNo

Return value

The length of the line, or -1 if lineNo was invalid.


wxTextCtrl::GetLineText

wxString GetLineText(long lineNo) const

Returns the contents of a given line in the text control, not including any trailing newline character(s).

Parameters

lineNo

Return value

The contents of the line.


wxTextCtrl::GetNumberOfLines

int GetNumberOfLines() const

Returns the number of lines in the text control buffer.

Remarks

Note that even empty text controls have one line (where the insertion point is), so GetNumberOfLines() never returns 0.

For wxGTK using GTK+ 1.2.x and earlier, the number of lines in a multi-line text control is calculated by actually counting newline characters in the buffer, i.e. this function returns the number of logical lines and doesn't depend on whether any of them are wrapped. For all the other platforms, the number of physical lines in the control is returned.

Also note that you may wish to avoid using functions that work with line numbers if you are working with controls that contain large amounts of text as this function has O(N) complexity for N being the number of lines.


wxTextCtrl::GetRange

virtual wxString GetRange(long from, long to) const

Returns the string containing the text starting in the positions from and up to to in the control. The positions must have been returned by another wxTextCtrl method.

Please note that the positions in a multiline wxTextCtrl do not correspond to the indices in the string returned by GetValue because of the different new line representations (CR or CR LF) and so this method should be used to obtain the correct results instead of extracting parts of the entire value. It may also be more efficient, especially if the control contains a lot of data.


wxTextCtrl::GetSelection

virtual void GetSelection(long* from, long* to) const

Gets the current selection span. If the returned values are equal, there was no selection.

Please note that the indices returned may be used with the other wxTextctrl methods but don't necessarily represent the correct indices into the string returned by GetValue() for multiline controls under Windows (at least,) you should use GetStringSelection() to get the selected text.

Parameters

from

to

wxPython note: The wxPython version of this method returns a tuple consisting of the from and to values.

wxPerl note: In wxPerl this method takes no parameter and returns a 2-element list ( from, to ).


wxTextCtrl::GetStringSelection

virtual wxString GetStringSelection()

Gets the text currently selected in the control. If there is no selection, the returned string is empty.


wxTextCtrl::GetStyle

bool GetStyle(long position, wxTextAttr& style)

Returns the style at this position in the text control. Not all platforms support this function.

Return value

true on success, false if an error occurred - it may also mean that the styles are not supported under this platform.

See also

wxTextCtrl::SetStyle, wxTextAttr


wxTextCtrl::GetValue

wxString GetValue() const

Gets the contents of the control. Notice that for a multiline text control, the lines will be separated by (Unix-style) \n characters, even under Windows where they are separated by a \r\n sequence in the native control.


wxTextCtrl::HitTest

wxTextCtrlHitTestResult HitTest(const wxPoint& pt, wxTextCoord *col, wxTextCoord *row) const

This function finds the character at the specified position expressed in pixels. If the return code is not wxTE_HT_UNKNOWN the row and column of the character closest to this position are returned in the col and row parameters (unless the pointers are NULL which is allowed).

Please note that this function is currently only implemented in wxUniv, wxMSW and wxGTK2 ports.

See also

PositionToXY, XYToPosition

wxPerl note: In wxPerl this function takes only the position argument and returns a 3-element list (result, col, row).


wxTextCtrl::IsEditable

bool IsEditable() const

Returns true if the controls contents may be edited by user (note that it always can be changed by the program), i.e. if the control hasn't been put in read-only mode by a previous call to SetEditable.


wxTextCtrl::IsEmpty

bool IsEmpty() const

Returns true if the control is currently empty. This is the same as GetValue().empty() but can be much more efficient for the multiline controls containing big amounts of text.

This function is new since wxWidgets version 2.7.1


wxTextCtrl::IsModified

bool IsModified() const

Returns true if the text has been modified by user. Note that calling SetValue doesn't make the control modified.

See also

MarkDirty


wxTextCtrl::IsMultiLine

bool IsMultiLine() const

Returns true if this is a multi line edit control and false otherwise.

See also

IsSingleLine


wxTextCtrl::IsSingleLine

bool IsSingleLine() const

Returns true if this is a single line edit control and false otherwise.

See also

IsMultiLine


wxTextCtrl::LoadFile

bool LoadFile(const wxString& filename, int fileType = wxTEXT_TYPE_ANY)

Loads and displays the named file, if it exists.

Parameters

filename

fileType

Return value

true if successful, false otherwise.


wxTextCtrl::MarkDirty

void MarkDirty()

Mark text as modified (dirty).

See also

IsModified


wxTextCtrl::OnDropFiles

void OnDropFiles(wxDropFilesEvent& event)

This event handler function implements default drag and drop behaviour, which is to load the first dropped file into the control.

Parameters

event

Remarks

This is not implemented on non-Windows platforms.

See also

wxDropFilesEvent


wxTextCtrl::Paste

virtual void Paste()

Pastes text from the clipboard to the text item.


wxTextCtrl::PositionToXY

bool PositionToXY(long pos, long *x, long *y) const

Converts given position to a zero-based column, line number pair.

Parameters

pos

x

y

Return value

true on success, false on failure (most likely due to a too large position parameter).

See also

wxTextCtrl::XYToPosition

wxPython note: In Python, PositionToXY() returns a tuple containing the x and y values, so (x,y) = PositionToXY() is equivalent to the call described above.

wxPerl note: In wxPerl this method only takes the pos parameter, and returns a 2-element list ( x, y ).


wxTextCtrl::Redo

virtual void Redo()

If there is a redo facility and the last operation can be redone, redoes the last operation. Does nothing if there is no redo facility.


wxTextCtrl::Remove

virtual void Remove(long from, long to)

Removes the text starting at the first given position up to (but not including) the character at the last position.

Parameters

from

to


wxTextCtrl::Replace

virtual void Replace(long from, long to, const wxString& value)

Replaces the text starting at the first position up to (but not including) the character at the last position with the given text.

Parameters

from

to

value


wxTextCtrl::SaveFile

bool SaveFile(const wxString& filename, int fileType = wxTEXT_TYPE_ANY)

Saves the contents of the control in a text file.

Parameters

filename

fileType

Return value

true if the operation was successful, false otherwise.


wxTextCtrl::SetDefaultStyle

bool SetDefaultStyle(const wxTextAttr& style)

Changes the default style to use for the new text which is going to be added to the control using WriteText or AppendText.

If either of the font, foreground, or background colour is not set in style, the values of the previous default style are used for them. If the previous default style didn't set them neither, the global font or colours of the text control itself are used as fall back.

However if the style parameter is the default wxTextAttr, then the default style is just reset (instead of being combined with the new style which wouldn't change it at all).

Parameters

style

Return value

true on success, false if an error occurred - may also mean that the styles are not supported under this platform.

See also

GetDefaultStyle


wxTextCtrl::SetEditable

virtual void SetEditable(const bool editable)

Makes the text item editable or read-only, overriding the wxTE_READONLY flag.

Parameters

editable

See also

IsEditable


wxTextCtrl::SetInsertionPoint

virtual void SetInsertionPoint(long pos)

Sets the insertion point at the given position.

Parameters

pos


wxTextCtrl::SetInsertionPointEnd

virtual void SetInsertionPointEnd()

Sets the insertion point at the end of the text control. This is equivalent to SetInsertionPoint(GetLastPosition()).


wxTextCtrl::SetMaxLength

virtual void SetMaxLength(unsigned long len)

This function sets the maximum number of characters the user can enter into the control. In other words, it allows to limit the text value length to len not counting the terminating NUL character.

If len is 0, the previously set max length limit, if any, is discarded and the user may enter as much text as the underlying native text control widget supports (typically at least 32Kb).

If the user tries to enter more characters into the text control when it already is filled up to the maximal length, a wxEVT_COMMAND_TEXT_MAXLEN event is sent to notify the program about it (giving it the possibility to show an explanatory message, for example) and the extra input is discarded.

Note that under GTK+, this function may only be used with single line text controls.

Compatibility

Only implemented in wxMSW/wxGTK starting with wxWidgets 2.3.2.


wxTextCtrl::SetModified

void SetModified(bool modified)

Marks the control as being modified by the user or not.

See also

MarkDirty, DiscardEdits


wxTextCtrl::SetSelection

virtual void SetSelection(long from, long to)

Selects the text starting at the first position up to (but not including) the character at the last position. If both parameters are equal to -1 all text in the control is selected.

Parameters

from

to


wxTextCtrl::SetStyle

bool SetStyle(long start, long end, const wxTextAttr& style)

Changes the style of the given range. If any attribute within style is not set, the corresponding attribute from GetDefaultStyle() is used.

Parameters

start

end

style

Return value

true on success, false if an error occurred - it may also mean that the styles are not supported under this platform.

See also

wxTextCtrl::GetStyle, wxTextAttr


wxTextCtrl::SetValue

virtual void SetValue(const wxString& value)

Sets the text value and marks the control as not-modified (which means that IsModified would return false immediately after the call to SetValue).

Note that this function will generate a wxEVT_COMMAND_TEXT_UPDATED event.

This function is deprecated and should not be used in new code. Please use the ChangeValue function instead.

Parameters

value


wxTextCtrl::ChangeValue

virtual void ChangeValue(const wxString& value)

Sets the text value and marks the control as not-modified (which means that IsModified would return false immediately after the call to SetValue).

Note that this function will not generate the wxEVT_COMMAND_TEXT_UPDATED event. This is the only difference with SetValue. See this topic for more information.

This function is new since wxWidgets version 2.7.1

Parameters

value


wxTextCtrl::ShowPosition

void ShowPosition(long pos)

Makes the line containing the given position visible.

Parameters

pos


wxTextCtrl::Undo

virtual void Undo()

If there is an undo facility and the last operation can be undone, undoes the last operation. Does nothing if there is no undo facility.


wxTextCtrl::WriteText

void WriteText(const wxString& text)

Writes the text into the text control at the current insertion position.

Parameters

text

Remarks

Newlines in the text string are the only control characters allowed, and they will cause appropriate line breaks. See wxTextCtrl::<< and wxTextCtrl::AppendText for more convenient ways of writing to the window.

After the write operation, the insertion point will be at the end of the inserted text, so subsequent write operations will be appended. To append text after the user may have interacted with the control, call wxTextCtrl::SetInsertionPointEnd before writing.


wxTextCtrl::XYToPosition

long XYToPosition(long x, long y)

Converts the given zero based column and line number to a position.

Parameters

x

y

Return value

The position value, or -1 if x or y was invalid.


wxTextCtrl::operator <<

wxTextCtrl& operator <<(const wxString& s)

wxTextCtrl& operator <<(int i)

wxTextCtrl& operator <<(long i)

wxTextCtrl& operator <<(float f)

wxTextCtrl& operator <<(double d)

wxTextCtrl& operator <<(char c)

Operator definitions for appending to a text control, for example:

  wxTextCtrl *wnd = new wxTextCtrl(my_frame);

  (*wnd) << "Welcome to text control number " << 1 << ".\n";