QString containing printer command in hex - qt

I am working on some printer driver and I am importing printer commands from command specification manual and for instance, printer command Print and Feed Paper has hexadecimal value of 0x0a:
#ifndef UECOMMANDSET_H
#define UECOMMANDSET_H
#include <QString>
namespace UeCommandSet
{
namespace TSM210
{
static const QString CMD_LF="\x0A";
} // namespace
} // namespace
#endif // UECOMMANDSET_H
Is this command representation corrent, i.e., will QString hold 0x0a value?

Yes, I tested it as follow:
static const QString CMD_LF= "\x0A";
qDebug() << CMD_LF.size();
qDebug() << (int)CMD_LF.at(0).toLatin1();
So, the first line gives 1, and second one gives 10 which is correct. Also you can use the following code to set CMD_LF to 0x0A
static const QString CMD_LF= "\n";

Related

How to write to struct from a GUI

Using Qt, I'm trying to write to my struct via inputs from a gui.
my target.h file:
struct Target{
double heading;
double speed;
};
my cpp:
#include <target.h>
struct Target myship;
myship.heading = 0;
myship.speed = 0;
I am using a QDial for the heading as an example. I can write the value of the QDial to a text file, but I would like to take advantage of structs.
What I'd like to know is how do I access, so that I can write to, the struct in my mainwindow.cpp?
I see that I can access my Target structure in mainwindow.cpp like this:
Target.heading
But it won't find "myship". I would have thought that I could have done
myship.heading...
or
Target.myship.heading...
But neither is working. When I do Target.heading it gives me the error
expected unqualified-id before '.' token
My ultimate goal is to have my gui (QDial in this case) write to the struct, and then have my gui (QLabel) display what has been written. As mentioned before, I have the read/write working with a text file, but I'm currently only writing out a single value, which isn't going to meet my requirements.
I'm new to Qt and structs in general so my guess is I'm missing something pretty trivial, or my understanding is off completely.
The struct prefix that you've used in the definition of the myship variable is a C-ism. It doesn't belong in C++. You should define myship as:
Target myship;
Furthermore, since it's 2016, you should use everything C++11 has got to make your life easier. Initialization of non-static/non-const class/struct members is very helpful and avoids boilerplate at the point of use of the struct. Thus, prefer:
// target.h
#include <QtCore>
struct Target {
double heading = 0.0;
double speed = 0.0;
};
QDebug operator(QDebug dbg, const Target & target);
// target.cpp
#include "target.h"
QDebug operator(QDebug dbg, const Target & target) {
return dbg << target.heading << target.speed;
}
// main.cpp
#include "target.h"
#include <QtCore>
int main() {
Target ship;
qDebug() << ship;
}
Note that you should include your own headers as #include "header.h", not #include <header.h>. The latter is reserved for system headers.
Without Qt:
#include <iostream>
struct Target {
double heading = 0.0;
double speed = 0.0;
};
int main() {
Target ship;
std::cout << ship.heading << " " << ship.speed << std::endl;
}

QJSEngine: print to console

I'm moving from QScriptEngine (which is deprecated) to QJSEngine, and I see that I'm unable to use print:
QJSEngine engine;
QJSValue val = engine.evaluate(
"print('123');"
);
if (val.isError()){
qDebug() << "error: " << val.toString();
}
qDebug() << "val: " << val.toVariant();
The output is:
error: "ReferenceError: print is not defined"
In QScriptEngine it works.
Then, what is the way to print something to console in QJSEngine? Can't find anything in docs. I tried to use console.log, but console is not defined as well.
From Qt 5.6 on, the solution is even easier: one can install Javascript extensions. One such extension is the console which provides a print function:
QJSEngine myEngine;
myEngine.installExtensions(QJSEngine::ConsoleExtension);
myEngine.eval("print(1 + 2)");
The print function is not implemented in QJSEngine. You will have to implement it yourself. Luckily you can write QObjects and make them available in your script. (See section "QObject Integration" at http://doc.qt.io/qt-5/qjsengine.html)
Here's how i've done it:
Create a class JSConsole inheriting from QObject:
Your own console class
jsconsole.h
#ifndef JSCONSOLE_H
#define JSCONSOLE_H
#include <QObject>
class JSConsole : public QObject
{
Q_OBJECT
public:
explicit JSConsole(QObject *parent = 0);
signals:
public slots:
void log(QString msg);
};
#endif // JSCONSOLE_H
jsconsole.cpp
#include "jsconsole.h"
#include <QDebug>
JSConsole::JSConsole(QObject *parent) :
QObject(parent)
{
}
void JSConsole::log(QString msg)
{
qDebug() << "jsConsole: "<< msg;
}
Using it
Now you create a proxy object in the js engine by using QJSEngine.newQObject.
After that you add it to your global object and use it.
QJSEngine engine;
JSConsole console;
QJSValue consoleObj = engine.newQObject(&console);
engine.globalObject().setProperty("console", consoleObj);
QJSValue result = engine.evaluate("console.log('test');");
Error logging
I've searched a long time for errors in my c++ code, when i just made a spelling error in my js file. The following snippet would have helped avoid that.
if (result.isError())
{
qDebug() << "result: " << result.property("lineNumber").toInt() << ":" << result.toString();
}
PS: First post after years of lurking. I've read tips on writing great answers but if I've made some mistakes/bad things please tell me.
May the code be with you

QSettings value method returns wrong QString

I have ordinrary text file with settings, which is generated by java application. Inside this file, there is a key db.url, which has value db.URL=jdbc\:mysql\://192.168.0.101\:3306/dbuser. I parse this file with QSettings class in QSettings::Native mode, everything is ok, but this db.URL gets messed up if I read it via value() method. Whatever I do (if I transform it into QString or QUrl), I get same result: jdbcmysql//192.,168.0.1013306/user. Why this key gets messed up?? I am using Qt 5.4 on Kubuntu 14.10 with kernel Linux desktop001 3.16.0-30-generic #40-Ubuntu SMP Mon Jan 12 22:06:37 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux. Here is a simple method that wrongly reads value of key:
QString UePOSSesttings::ueReadDbUrl() const
{
// QVariant dbUrl=this->value(UeDefaults::UeDbKeys::KEY_DB_URL);
return this->value(UeDefaults::UeDbKeys::KEY_DB_URL).toString();
}
and constants:
#ifndef UEDEFAULTS
#define UEDEFAULTS
#include <QString>
namespace UeDefaults
{
namespace UeDbKeys
{
static const QString KEY_DB_DRIVER="db.driver";
static const QString KEY_DB_PASSWORD="db.password";
static const QString KEY_DB_URL="db.URL";
static const QString KEY_DB_DRIVER_LIB="db.driverlib";
static const QString KEY_DB_ENGINE="db.engine";
static const QString KEY_DB_USER="db.user";
}
}
#endif // UEDEFAULTS
QSettings clears up the string from unsupported escape sequences, in this case \:. Remove \ slashes before reading the value or don't use QSettings for parsing unsupported file formats.
Perhaps not the most optimal solution but you could processes the settings file to escape all \: before reading it with QSettings.
QFile oldSettings("settings.txt");
oldSettings.open(QIODevice::ReadOnly);
QString data = QString::fromAscii(oldSettings.readAll().constData());
oldSettings.close();
data.replace("\\:", "\\\\:");
QFile newSettings("/tmp/settings.txt");
newSettings.open(QIODevice::WriteOnly);
newSettings.write(data.toAscii(), data.size());
newSettings.close();
I did it:
void UePOSSesttings::ueParseData(const QString& filename)
{
QFile settingsFile(filename);
QString data;
settingsFile.open(QIODevice::ReadOnly);
data=QString::fromLatin1(settingsFile.readAll().constData());
data.replace("\\:",
":");
this->ueSetParsedData(data);
qDebug() << this->ueParsedData();
settingsFile.close();
}
and now I get this url:
db.URL=jdbc:mysql://192.168.0.101:3306/dbuser
which is ok!

How to I get the UTF-8 data into a QString

via server API's i'm getting contact information using member of structure:
char displayName[USERNAME_MAX_SIZE];
One of those names is a European name with special characters: "Per SpÄnt"
the structure of the displayName is as follows:
When I import 'displayName' into a QString via the "fromUtf8" function, I am getting the following QString:
How can I get the correct string into my QString without converting the special character into two weird characters?
FWIW, this is what works and doesn't work for me using Qt 4.7.4.
#include <iostream>
#include <string>
#include <QDebug>
#include <QString>
int main()
{
char name[7] = "Sp__nt";
name[2]=-61;
name[3]=-91;
std::cout << name << std::endl; // works
qDebug() << QString::fromUtf8( name ); // does not work
qDebug() << QString::fromAscii( name ); // works
qDebug() << QString::fromLatin1( name ); // works
qDebug() << QString::fromStdString( name ); // works
return 0;
}

Serializing QHash to QByteArray

I am trying to serialize a QHash object and store it in a QByteArray (to be sent using QUDPSocket or QTCPSocket).
My current attempt looks like this:
// main.cpp
#include <QtCore/QCoreApplication>
#include <QHash>
#include <QVariant>
#include <QDebug>
int main(int argc, char *argv[])
{
QHash<QString,QVariant> hash;
hash.insert("Key1",1);
hash.insert("Key2","thing2");
QByteArray ba;
QDataStream ds(&ba, QIODevice::WriteOnly);
ds << hash;
qDebug() << ds;
}
When this runs I get this out of qDebug():
QIODevice::read: WriteOnly device
QIODevice::read: WriteOnly device
QIODevice::read: WriteOnly device
QVariant(, )
The documentation says that this should write to the byte array, but obviously that isn't happening here. What am I doing wrong?
Qt 4.7.1 on OS-X
Thanks!
-J
The reason it is failing is because it is trying to read from a write-only stream. The sequence is:
qDebug() << ds;
--> QVariant::QVariant(QDataStream &s)
--> QDataStream& operator>>(QDataStream &s, QVariant &p)
--> void QVariant::load(QDataStream &s)
That last method (and some more downstream) try to read from the data stream to convert its contents into a QVariant for display in qDebug. In other words, your actual code is fine; the debugging check is causing the failure.
You could check the contents of the byte array with something like:
qDebug() << ba.length() << ba.toHex();
You can Implement you program like this code:
QHash<QString,QVariant> options;
options["string"] = "my string";
options["bool"] = true;
QByteArray ar;
//Serializing
QDataStream out(&ar,QIODevice::WriteOnly); // write the data
out << options;
//setting a new value
options["string"] = "new string";
//Deserializing
// read the data serialized from the file
QDataStream in(&ar,QIODevice::ReadOnly);
in >> options;
qDebug() << "value: " << options.value("string");
ref

Resources