Conversiones entre Tipos de C++ y wxWidgets
Cuando trabajamos con wxWidgets es habitual tener que convertir datos entre los tipos estándar de C++ y los tipos propios del framework.
En este artículo repasaremos las conversiones más comunes que encontrarás en aplicaciones reales.
std::string ↔ wxString
Probablemente la conversión más frecuente.
std::string a wxString
std::string texto = "Hola mundo";
wxString wxtexto(texto);
También puede hacerse explícitamente:
wxString wxtexto = wxString::FromUTF8(texto);
Esta última opción es preferible cuando sabemos que el contenido está codificado en UTF-8.
wxString a std::string
wxString texto = "Hola mundo";
std::string str = texto.ToStdString();
Si necesitamos UTF-8:
std::string str = texto.ToUTF8().data();
const char* ↔ wxString
const char* a wxString
const char* texto = "Hola";
wxString wxtexto(texto);
O usando UTF-8:
wxString wxtexto = wxString::FromUTF8(texto);wxString a const char*
wxString texto = "Hola";
const char* ptr = texto.mb_str();
Para UTF-8:
const char* ptr = texto.utf8_string();
int ↔ wxString
int a wxString
int numero = 123;
wxString texto = wxString::Format("%d", numero);
También:
wxString texto = std::to_string(numero);wxString a int
wxString texto = "123";
long valor;
if (texto.ToLong(&valor))
{
// Conversión exitosa
}
double ↔ wxString
double a wxString
double precio = 123.45;
wxString texto = wxString::Format("%.2f", precio);wxString a double
wxString texto = "123.45";
double valor;
if (texto.ToDouble(&valor))
{
// Conversión exitosa
}
bool ↔ wxString
bool a wxString
bool activo = true;
wxString texto = activo ? "true" : "false";wxString a bool
wxString texto = "true";
bool activo = texto.CmpNoCase("true") == 0;
std::vector
Los contenedores estándar funcionan perfectamente con wxString.
std::vector<wxString> nombres;
nombres.push_back("Juan");
nombres.push_back("Ana");
wxArrayString ↔ std::vector
wxArrayString a std::vector
wxArrayString array;
array.Add("Uno");
array.Add("Dos");
std::vector<wxString> vec(
array.begin(),
array.end()
);std::vector a wxArrayString
std::vector<wxString> vec =
{
"Uno",
"Dos"
};
wxArrayString array;
for (const auto& item : vec)
{
array.Add(item);
}
SQLite y wxString
Cuando trabajamos con SQLite suele ser necesario convertir cadenas.
Guardar datos
sqlite3_bind_text(
stmt,
1,
nombre.utf8_string(),
-1,
SQLITE_TRANSIENT
);Leer datos
const char* texto =
reinterpret_cast<const char*>(
sqlite3_column_text(stmt, 0)
);
wxString nombre =
wxString::FromUTF8(texto);
wxDateTime ↔ wxString
Fecha a texto
wxDateTime fecha = wxDateTime::Now();
wxString texto =
fecha.FormatISODate();
Resultado:
2026-06-07Texto a fecha
wxDateTime fecha;
fecha.ParseISODate(
"2026-06-07"
);
wxDateTime ↔ std::chrono
A partir de C++20 es frecuente combinar wxWidgets con std::chrono.
auto ahora =
std::chrono::system_clock::now();
Para interoperar suele ser necesario trabajar mediante timestamps Unix.
wxDateTime fecha =
wxDateTime::Now();
time_t unixTime =
fecha.GetTicks();
Conversión de punteros
En wxWidgets es habitual obtener punteros a clases derivadas.
wxWindow* ventana =
FindWindow(ID_CLIENTE);
wxTextCtrl* txtNombre =
dynamic_cast<wxTextCtrl*>(ventana);
if (txtNombre)
{
txtNombre->SetValue("Juan");
}
Conversión desde controles
Una operación extremadamente común consiste en leer un valor desde un control.
wxString texto =
txtImporte->GetValue();
Convertir a entero:
long importe;
if (texto.ToLong(&importe))
{
// OK
}
Convertir a decimal:
double importe;
if (texto.ToDouble(&importe))
{
// OK
}
Buenas Prácticas
- Utilizar UTF-8 siempre que sea posible.
- Preferir
ToLong()yToDouble()antes que funciones comoatoi()oatof(). - Evitar conversiones innecesarias entre
wxStringystd::string. - Mantener internamente un único formato de texto cuando sea posible.
- Verificar siempre el resultado de las conversiones numéricas.
- Utilizar
dynamic_castcuando se trabaje con jerarquías de controles.
Resumen
Las conversiones más utilizadas en wxWidgets son:
| Desde | Hacia |
|---|---|
| std::string | wxString |
| wxString | std::string |
| const char* | wxString |
| wxString | const char* |
| int | wxString |
| wxString | int |
| double | wxString |
| wxString | double |
| wxArrayString | std::vector |
| wxDateTime | wxString |
Dominar estas conversiones simplifica enormemente el desarrollo de interfaces gráficas, bases de datos y aplicaciones empresariales construidas con wxWidgets.