Accents with QString on Qt 5.9 result in bizarre characters
-
Hi, good afternoon, to a doubt that I can't tidy at all The code is as follows. ...
QTextStream stream( &file ); stream.setCodec("ISO 8859-1"); stream << "<p align=center><font size=4><font face=times><b>PROCURAÇÃO AD JUDICIA E ET EXTRA</b></font></font></center>" << ent << ent << ent << "<font size=3,25><font face=times><p align=justify> Por este instrumento particular, ", << "<b>" << noM << "</b>" << " brasileiro(a), " << ciV << ", " << emP<< ", portador(a) da Cédula de Identidade número RG n. " << rG /*"<<, nascido em: "<<*/ << ", inscrito(a) no CPF sob n. " << cpF << ", PIS " << piS << ", CTPS / N. / Série " << ctpS << ", e-mail: <u>" << emA << "</u>, residente e domiciliado(a) na " << enD << ", " << ceP<< " - " << ciD << "/" << esT<< ", nomeia e constitui como seus procuradores e advogados, <b>Antônio Sérgio Meorin - OAB/SP n. 328.518 e Júlio César Lopes de Araújo - OAB/SP n. 379.678</b>, ambos, com escritório profissional situado na Rua Paraíba, 583, Centro, São Joaquim da Barra/SP, aos quais confere os poderes da presente procuração para o foro em geral, inclusive o <i>et extra</i>, para, independente da ordem de nomeação, agir em nome do(a) outorgante, em quaisquer Juízos, instâncias, Tribunais, Repartições Públicas, com amplos e ilimitados poderes, podendo propor as ações competentes e defendê-o(a) nas contrárias, seguinda umas e outras até final decisão, usando os recursos, desistindo ou dispensando-os, podendo praticar todos os atos que se tornarem necessários, ao útil, bom e fiel desempenho deste mandato, inclusive substavelecer, com ou sem reservas de poderes, receber intimação, confessar, reconhecer a procedência do pedido, transigir, desistir, renunciar, receber e dar recibo, dar quitação, acordar e firmar compromisso." << ent << ent << "Declaro, para os fins de concessão dos benefícios da Justiça Gratuita que, em conformidade com o disposto na CF de 88, artigo 5º, LXXIV e Leis n.º1060/50 e 7.115/83, <u>sob as penas da lei</u>, art. 299 do CP, que sou pessoa <b>pobre</b>, na <u>acepção legal exata do termo</u>, cuja situação financeira não permite pagar as custas do processo, sem prejuízo do sustento próprio ou da família." << ent << ent << "Por ser verdade, e para que surta seus legais e jurídicos efeitos, assina a presente, nesta data, sob as penas da lei." << ent << ent << "<p align=left>São Joaquim da Barra/SP, " << proC << "." << ent << ent << ent << ent << "<center><b>______________________________________</b></center>" << ent << "<center>OUTORGANTE</center></b></font></font>" ;
until then all right, despite the mess (I'm starting and I don't know how to skip lines without breaking the code) the code works, the typed in the stream, after setCodec becomes normal, however, the set codec does not transform the variability I created in QString, bug the accents, for example the name:
For this particular instrument, OT?IO JEFERS? Brazilian(a), single(a), 561, bearer(a) Cedula
The name should leave "THEVIO JEFERSÃO", however, it is replaced by ?, while the rest comes out normally, as the "Cédula" which was rifada.... what's going on, and how can I fix it? If I seal the codec to UTF-8, the variable becomes normal and the rest of the text gets all buzzed. ... what solution? To that for days...
follows the list of the variables created:
QString noM = ui->lineNome->text().toUpper(); QString ceP = ui->lineCep->text(); QString ciD = ui->lineCid->text(); QString cpF = ui->lineCpf->text(); QString ctpS = ui->lineCtps->text(); QString rG = ui->lineRg->text(); QString enD = ui->lineEnd->text(); QString esT = ui->boxEst->currentText(); QDate daT = ui->dateDat->date(); QString nuM = ui->lineNum->text(); QString ciV = ui->boxCiv->currentText(); QString emP = ui->lineEmp->text().toLower(); QString comP = (nuM) + (" - ") + (noM); QString piS = ui->linePis->text(); QString emA = ui->lineEma->text(); QString proC = ui->lineProc->text();
Thank you, from now on, I accept suggestions for learning materials!
-
There are 2 reasons why this occurs:
It's because
QString
internally works withlatin1
, the other reason is thatAll files generated by QtCreator are encoded in UTF-8, i.e. even the
.cpp
and.h
So when trying to merge the data from
.cpp
that in the case are these:stream << "<p align=center><font size=4><font face=times><b>PROCURAÇÃO...
And when the value of
ui->lineNome->text()
for oneQString
you will be working with different encodings if your "html" was sealed in aQString
before passing onQTextStream
.Then
.cpp
where you wrote your "HTML" within the stream this in UTF-8 andui->lineNome->text()
Must be latin1. When you try to decode with:stream.setCodec("ISO-8859-1");
Or something like it will affect the whole
stream
, and since it has unicode mixed with latin1 it will try to decode something that is already decoded, generating the interrogation signs asOT?IO JEFERS?
I did a test, I opened my
.cpp
, created by QtCreator even a project, with the following content:#include "widget.h" #include "ui_widget.h" #include <QFile> #include <QTextStream>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);QObject::connect(ui->btnSave, SIGNAL(pressed()), this, SLOT(save()));
}
Widget::~Widget()
{
delete ui;
}void Widget::save()
{
QString filename = "data.txt";
QFile file(filename);if (file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); stream << "Titulo:" << "Olá mundo!" << endl; stream << "Nome:" << ui->nomeDoCliente->text() << endl; file.close(); }
}
Open it.
widget.cpp
by the sublimetext and he showed utf8, as in the image:Compilei and executed the program, then in the field
nomeDoCliente
I'.Á É Í Ó Ú
and clicked on the save button you ranWidget::save
, the content generated was this:Titulo:Olá mundo!
Nome:Á É Í Ó Ú
And in the sublimetext shows it being as windows-1252, i.e.
Olá
are characters of utf-8 mixed with latin1Then I saved the
widget.cpp
as iso-8859-1 (compatible with latin1) by the sublimetext, he stayed like this:Then I recompiled the entire project, ran the program and click save, the
data.txt
now has this content:Titulo:Olá mundo!
Nome:Á É Í Ó Ú
See, it wasn't necessary
setCodec
or nothing, the filedata.txt
stayed with the perfect accents and the sublimetext he accuses as windows-1252 (compatible with latin1).How to solve
However get open one by one of your
.cpp
and saving as windows-1252 or iso-8859-1 is not easy task, even more if using QtCreator, to simplify just leave all values inQString
always because so it will use the default encoding always, see an example that worked:void Widget::save()
{
QString textopadrao = "Olá mundo!";
QString nome = ui->nomeDoCliente->text();if (file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); stream << "Titulo:" << textopadrao << endl; stream << "Nome:" << nome << endl; file.close(); }
}
After saving both the value coming from
nomeDoCliente
what was intextopadrao
used the same coding.Then do this in your code (add line breaks because it gets easier):
QString conteudoHtml = ""
"<p align=center><font size=4><font face=times><b>"
"PROCURAÇÃO AD JUDICIA E ET EXTRA</b></font></font></center>"
"" + ent + ent + ent + "<font size=3,25><font face=times>"
"<p align=justify> Por este instrumento particular, " + "<b>"
"" + noM + "</b>" + " brasileiro(a), " + ciV + ", " + emP + ""
", portador(a) da Cédula de Identidade número RG n. rG "
"nascido em: " + ", inscrito(a) no CPF sob n. " + cpF + ", PIS "
"" + piS + ", CTPS / N. / Série " + ctpS + ", e-mail: <u>" + emA + ""
"</u>, residente e domiciliado(a) na " + enD + ", " + ceP + " - "
"" + ciD + "/" + esT + ", nomeia e constitui como seus procuradores e advogados,"
" <b>Antônio Sérgio Meorin - OAB/SP n. 328.518 e Júlio César Lopes de Araújo -"
" OAB/SP n. 379.678</b>, ambos, com escritório profissional situado na Rua"
" Paraíba, 583, Centro, São Joaquim da Barra/SP, aos quais confere os poderes"
" da presente procuração para o foro em geral, inclusive o <i>et extra</i>,"
" para, independente da ordem de nomeação, agir em nome do(a) outorgante, em"
" quaisquer Juízos, instâncias, Tribunais, Repartições Públicas, com amplos e"
" ilimitados poderes, podendo propor as ações competentes e defendê-o(a) nas"
" contrárias, seguinda umas e outras até final decisão, usando os recursos,"
" desistindo ou dispensando-os, podendo praticar todos os atos que se tornarem"
" necessários, ao útil, bom e fiel desempenho deste mandato, inclusive"
" substavelecer, com ou sem reservas de poderes, receber intimação, confessar,"
" reconhecer a procedência do pedido, transigir, desistir, renunciar, receber e"
" dar recibo, dar quitação, acordar e firmar compromisso." + ent + ent + ""
" Declaro, para os fins de concessão dos benefícios da Justiça Gratuita que, em"
" conformidade com o disposto na CF de 88, artigo 5º, LXXIV e Leis n.º1060/50 e"
" 7.115/83, <u>sob as penas da lei</u>, art. 299 do CP, que sou pessoa <b>pobre</b>,"
" na <u>acepção legal exata do termo</u>, cuja situação financeira não permite"
" pagar as custas do processo, sem prejuízo do sustento próprio ou da família."
"" + ent + ent + "Por ser verdade, e para que surta seus legais e jurídicos efeitos,"
" assina a presente, nesta data, sob as penas da lei." + ent + ent + ""
"<p align=left>São Joaquim da Barra/SP, " + proC + "." + ent + ent + ent + ""
"" + ent + "<center><b>______________________________________</b></center>" + ent + ""
"<center>OUTORGANTE</center></b></font></font>";if (file.open(QIODevice::WriteOnly)) {
QTextStream stream(&file);
stream << conteudoHtml << endl;
file.close();
}
If you want to save as UTF-8 just do this:
if (file.open(QIODevice::WriteOnly)) {
QTextStream stream(&file);
stream.setCodec("UTF-8");
stream << conteudoHtml << endl;
file.close();
}
I did the test and worked perfectly, note that for tests I seveni all variables with the value of the field "Name" that in the case was this
"isso é um teste blá á ã ô"
, and worked perfectly generating this result indata.txt
:<p align=center><font size=4><font face=times><b>PROCURAÇÃO AD JUDICIA E ET EXTRA</b></font></font></center>
<font size=3,25><font face=times><p align=justify> Por este instrumento particular, <b>"isso é um teste blá á ã ô"</b> brasileiro(a), "isso é um teste blá á ã ô", "isso é um teste blá á ã ô", portador(a) da Cédula de Identidade número RG n. rG nascido em: , inscrito(a) no CPF sob n. "isso é um teste blá á ã ô", PIS "isso é um teste blá á ã ô", CTPS / N. / Série "isso é um teste blá á ã ô", e-mail: <u>"isso é um teste blá á ã ô"</u>, residente e domiciliado(a) na "isso é um teste blá á ã ô", "isso é um teste blá á ã ô" - "isso é um teste blá á ã ô"/"isso é um teste blá á ã ô", nomeia e constitui como seus procuradores e advogados, <b>Antônio Sérgio Meorin - OAB/SP n. 328.518 e Júlio César Lopes de Araújo - OAB/SP n. 379.678</b>, ambos, com escritório profissional situado na Rua Paraíba, 583, Centro, São Joaquim da Barra/SP, aos quais confere os poderes da presente procuração para o foro em geral, inclusive o <i>et extra</i>, para, independente da ordem de nomeação, agir em nome do(a) outorgante, em quaisquer Juízos, instâncias, Tribunais, Repartições Públicas, com amplos e ilimitados poderes, podendo propor as ações competentes e defendê-o(a) nas contrárias, seguinda umas e outras até final decisão, usando os recursos, desistindo ou dispensando-os, podendo praticar todos os atos que se tornarem necessários, ao útil, bom e fiel desempenho deste mandato, inclusive substavelecer, com ou sem reservas de poderes, receber intimação, confessar, reconhecer a procedência do pedido, transigir, desistir, renunciar, receber e dar recibo, dar quitação, acordar e firmar compromisso.
Declaro, para os fins de concessão dos benefícios da Justiça Gratuita que, em conformidade com o disposto na CF de 88, artigo 5º, LXXIV e Leis n.º1060/50 e 7.115/83, <u>sob as penas da lei</u>, art. 299 do CP, que sou pessoa <b>pobre</b>, na <u>acepção legal exata do termo</u>, cuja situação financeira não permite pagar as custas do processo, sem prejuízo do sustento próprio ou da família.
Por ser verdade, e para que surta seus legais e jurídicos efeitos, assina a presente, nesta data, sob as penas da lei.
<p align=left>São Joaquim da Barra/SP, "isso é um teste blá á ã ô".
<center><b>______________________________________</b></center>
<center>OUTORGANTE</center></b></font></font>