Qt json parser return parse error - qt

I try to parse json string using this method:
QString ourJSONData = QString('{"couchdb":"Welcome","version":"1.0.1"}');
QString response = QString("[") + QString(ourJSONData) + QString("]");
QScriptEngine engine;
QScriptValue sc = engine.evaluate(response);
ui->label->setText(sc.toString());
But label return
SyntaxError: Parse error
I using Qt 4.7.4
What i do wrong? Thanks.
UPD:
Sorry, problem was in that string:
QString ourJSONData = QString('{"couchdb":"Welcome","version":"1.0.1"}');
need change to:
QString ourJSONData = QString("{\"couchdb\":\"Welcome\",\"version\":\"1.0.1\"}");
P.S. this method i found at http://blog.siegerstein.com/archives/134

I built your code in QtCreator in got a very helpful error message:
character constant too long for its type
It's because your ourJSONData variable is initialised with a text in single quotes, which is for single characters.
This will correct that initialisation. (I put a \ before each double-quote, and then changed the single-quotes to double):
QString ourJSONData = QString("{\"couchdb\":\"Welcome\",\"version\":\"1.0.1\"}");

Related

Error c2440: cannot convert const char[4] to char*

i have a question:
I have a code in QT Creator (build in MSVC2013) that first work perfectly, now in other computer with an updated QT Creator (build in MSVC2015) when try tu rungive me this error:
"error: C2664: 'wave_object wave_init(char *)': cannot convert
argument 1 from 'const char [4]' to 'char *'" "Conversion from string
literal loses const qualifier (see /Zc:strictStrings)"
Error is in this part of the code:
wave_object db4;
wt_object wt;
db4 = wave_init("db4");
wt = wt_init(db4, "dwt", N, 4);
setDWTExtension(wt, "sym");
setWTConv(wt, "direct");
The definition of the method is here:
wave_object wave_init(char* wname) {
wave_object obj = NULL;
int retval;
retval = 0;
if (wname != NULL) {
retval = filtlength(wname);
}
I compile this with MinGW and dont have error, in the computer with QT Creator builded with MSVC2013 work fine also with the MSVC2013 compiler but now with the QT Creator builded with MSVC2015 appears this error with the MSVC2015 compiler.
I need to use the same compiler that was builded QT Creator because I am using QWT Plugins and is necessary to use the same compiler.
Thank you for your help! =)
In your function call:
db4 = wave_init("db4");
The "db4" argument is string literal, and is in a strict sense const.
Your definition of the function:
wave_object wave_init(char* wname)
does not identify parameter wname as const.
Modify as follows:
wave_object wave_init(const char* wname)

Problems in converting to UTF-8 in Qt

I try to show a persian string in Qt:
QMessageBox msg;
QString str = "یا حسین";
msg.setText(QString::fromUtf8(str));
msg.exec();
but it shows the following error :
/home/msi/Desktop/VoMail
Project/Project/VoMail-build-desktop-Qt_4_8_1_in_PATH__System__Release/../VoMail/mainwindow.cpp:40:
error: no matching function for call to 'QString::fromUtf8(QString&)'
I want to use a string variable, and not a string directly.
How can I convert a QString variable to Utf8?
As seen here, QString::fromUtf8() does not accept an argument of type QString. You must give it a const char *, so you could rewrite it like this:
QMessageBox msg;
QString str = QString::fromUtf8("یا حسین");
msg.setText(str);
msg.exec();
its not good idea write like that
using this must be better
QString str(tr("ya hossein");
and use linguist and add persian translation file to your project http://qt-project.org/doc/qt-4.8/linguist-translators.html
and if you dont want use this, you must be sure your IDE or code editor (like qtcreator) use utf8 for saving files and just use
QString str("یا حسین");
it must be ok, i tested that so many times

Qt ActiveX "Unknown error"

I'm working on integrating T-Cube motor controller (http://www.thorlabs.de/newgrouppage9.cfm?objectgroup_id=2419) into the software based on Qt-4.8.1 package. Due to there is no manual or any sort of tutorial how to retrieve ActiveX object and how to call methods I did the following.
1) Looked through Windows registry looking for words similar to motor controller name. Found a candidate with CLSID "{3CE35BF3-1E13-4D2C-8C0B-DEF6314420B3}".
2) Tried initializing it in the following way (code provided is shortened, all result checks are removed in order to improve readability):
HRESULT h_result = CoInitializeEx(NULL, COINIT_MULTITHREADED);
pd->moto = new QAxObject();
initialized = moto->setControl( "{3CE35BF3-1E13-4D2C-8C0B-DEF6314420B3}" );
QString stri = browser->generateDocumentation();
obj->dynamicCall("SetHWSerialNum(int)", params);
QVariantList params;
params << 0;
params << 0.0;
int result = pd->moto->dynamicCall("GetPosition(int, double&)", params).toInt();
value = params[1].toFloat();
QVariantList params;
params << 0;
params << dist;
params << dist;
params << true;
int result = pd->moto->dynamicCall("MoveRelativeEx(int, double, double, bool)", params).toInt();
3) generateDocumentation() method gives perfect description of ~150 methods.
4) All dynamicCall() invocations cause "Error calling ...: Unknown error", where "..." is a first argument of dynamicCall() from the list generateDocumentation()'s given me.
5) If I insert into dynamicCall() any method which isn't presented in the documentation generated the output is different. So I suppose that methods in documentation generated really exist.
6) If I use #import directive and try calling directly avoiding QAxObject usage I see "mg17motor.tlh" file but none of interfaces described there contain any methods. So I can't use it directly as well. Is it normal?
I would be very much obliged for any advice.
You can find the ActiveX object using the OLE viewer. Then search for something like
APT.. or MG.. under all objects. Then find the parameter ProgID=MGMOTOR.MGMotorCtrl.1.
Now in Qt don't use QAxObject but QAxWidget. Then you get something like:
QAxWidget* aptMotor;
QVariant chanID = QVariant(0);
aptMotor = new QAxWidget();
aptMotor->setControl("MGMOTOR.MGMotorCtrl.1");
//Nice html documentation on available functions
QFile file("out.html");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << aptMotor->generateDocumentation();
file.close();
aptMotor->setProperty("HWSerialNum",QVariant(83853493));
aptMotor->dynamicCall("StartCtrl");
aptMotor->dynamicCall("EnableHWChannel(QVariant)",chanID);
QThread::sleep(1); // Give it time to enable the channel
double pos(0);
aptMotor->dynamicCall("SetAbsMovePos(QVariant,QVariant)",chanID,QVariant(pos));
aptMotor->dynamicCall("MoveAbsolute(QVariant,QVariant,QVariant)",chanID,0);
aptMotor->dynamicCall("StopCtrl");

force call to QString(const char *) constructor in Qt 4.7

I am trying to compile a library written in Qt 4.6. On my current Linux machine I have only Qt 4.7 installed. The following code part:
/*file try.h*/
void fileOpen(QString s = NULL) ;
/*file try.cpp*/
void MainWindow::fileOpen(QString s) {
QString filename ;
if(s.isNull()) filename = QFileDialog::getOpenFileName(
this,
"Choose a file",
".",
"Source file (*.)");
else filename = s ;
}
compiles with the following error (I used cmake but the corresponding line code is the one listed above):
In member function ‘virtual int MainWindow::qt_metacall(QMetaObject::Call, int,
void**)’:
/homes/combi/hodorog/Developments/axelOld/build/axel/src/QGui/moc_MainWindow.cxx:141:26:
error: conversion from ‘long int’ to ‘QString’ is ambiguous
/homes/combi/hodorog/Developments/axelOld/build/axel/src/QGui/moc_MainWindow.cxx:141:26:
note: candidates are:
/usr/include/QtCore/qstring.h:426:43: note: QString::QString(const char*)
/usr/include/QtCore/qstring.h:105:14: note: QString::QString(const QChar*)
So I am guessing the problem is that in qt. 4.7. there are two QString constructors that can take a pointer as an argument (as listed in the compilation error), whereas in qt 4.6. there is only one QString constructor that can take a pointer as an argument. How can I force QString to call the constructor with const char * as an argument?
Thank a lot for your help in advance,
madalina
void fileOpen(QString s = NULL);
You are trying to construct a QString object with 0. It seems you are confusing the null of pointers with a null QString. A null QString is one which is created with the constructor QString(). Given how your function is implemented (referring to s.isNull()), you should change the function declaration to
void fileOpen(QString s = QString());

How to append this in Qt?

I want to add a new line in this. This is my sample code:
ui->button->setText(" Tips " + "\n" + TipsCount );
This is the error it shows:
invalid operands of types 'const char [7]' and 'const char [2]' to binary 'operator+'
But when I add to label it gets appended!
ui->label->setText(name + "\n" + City );
Can someone please help me?
This is a very common problem in C++ (in general, not just QT).
Thanks to the magic of operator overloading, name + "\n" gets turned into a method call (couldn't say which one since you don't list the type). In other words, because one of the two things is an object with + overloaded it works.
However when you try to do "abc" + "de", it blows up. The reason is because the compiler attempts to add two arrays together. It doesn't understand that you mean concatenation, and tries to treat it as an arithmetic operation.
To correct this, wrap your string literals in the appropriate string object type (std::string or QString most likely).
Here is a little case study:
QString h = "Hello"; // works
QString w = "World"; // works too, of course
QString a = h + "World"; // works
QString b = "Hello" + w; // also works
QString c = "Hello" + "World"; // does not work
String literals in C++ (text in quotes) are not objects and don't have methods...just like numeric values aren't objects. To make a string start acting "object-like" it has to get wrapped up into an object. QString is one of those wrapping objects, as is the std::string in C++.
Yet the behavior you see in a and b show we're somehow able to add a string literal to an object. That comes from the fact that Qt has defined global operator overloads for both the case where the left operand is a QString with the right a const char*:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-24
...as well as the other case where the left is a const char* and the right is a QString:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-27
If those did not exist then you would have had to write:
QString a = h + QString("World");
QString b = QString("Hello") + w;
You could still do that if you want. In that case what you'll cause to run will be the addition overload for both operands as QString:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-24
But if even that didn't exist, you'd have to call a member function. For instance, append():
http://doc.qt.nokia.com/latest/qstring.html#append
In fact, you might notice that there's no overload for appending an integer to a string. (There's one for a char, however.) So if your TipsCount is an integer, you'll have to find some way of turning it into a QString. The static number() methods are one way.
http://doc.qt.nokia.com/latest/qstring.html#number
So you might find you need:
ui->button->setText(QString(" Tips ") + "\n" + QString::number(TipsCount));

Resources