user1129812
user1129812

Reputation: 2889

Qt: How to use the returned QVariant from evaluateJavaScript?

I am using Qt 4.8.1 with the evaluateJavaScript function to want to get some DOM elements back into a Qt application. The code I used is :

QVariant paragraphs = view->page()->mainFrame()->evaluateJavaScript("document.getElementsByTagName(\"p\")");
const char* returnTypeName = paragraphs.typeName();
std::cout << "returnTypeName = " << returnTypeName << std::endl;

I find that :

returnTypeName = QVariantMap

However, I do not know the actual return type in the QVariantMap.

I want to know that could I find out the actual type in the returned QVariantMap ? Could I convert the QVariantMap to a QWebElement / QWebElementCollection ? Or how could I use the returned QVariantMap (as I have no experience in using QVariant objects).

Thanks for any suggestion.

Upvotes: 1

Views: 1586

Answers (2)

Username Obfuscation
Username Obfuscation

Reputation: 777

As JKSH suggested, if you want to pull a DOM element into Qt in a useful form for manipulating that object, you can't use a Javascript evaluation to do so, as a Javascript element reference can't be converted into a QWebElement object.

To obtain a DOM element in Qt, you need to use Qt methods directly. This code should return the QWebElementCollection you were looking for without the need for a Javascript evaluation:

QWebElementCollection paragraphs = view->page()->mainFrame()->documentElement().findAll("p");

Upvotes: 1

JKSH
JKSH

Reputation: 2718

The first thing you should do is consult the QVariant documentation. Qt documentation is very comprehensive; make good use of it.

Anyway, a QVariantMap is a typedef of QMap<QString, QVariant>. So, you use string keys (variable names) to extract individual values.

// Convert your result into the underlying map
QVariantMap returnedMap = paragraphs.toMap();

// Get some values
QVariant value1 = returnedMap["key1"];
QVariant value2 = returnedMap["key2"];

// Find out their types
std::cout << "Type 1 = " << value1.typeName() << std::endl;
std::cout << "Type 2 = " << value1.typeName() << std::endl;

// Convert them to their underlying types
// (assuming value1 is a string, value2 is an int)
QString str = value1.toString();
int number = value2.toInt();

Upvotes: 2

Related Questions