Qt a nonstatic member reference must be relative to a specific object - qt

I have a function which calls emitResult after loading data from file.
bool IpResolver::ResolvedInfo::load(QTextStream &in)
{
ResolvedInfo rf;
while (!in.atEnd())
{
QString line = in.readLine();
QStringList list = line.split(' ');
list[0] = rf.country;
list[1] = rf.ip;
if (rf.ip.isEmpty() == false)
{
emitResult(rf);
}
}
}
So here is declaration of emitResult:
private:
void emitResult(const ResolvedInfo &data);
And it gives me this error:
a nonstatic member reference must be relative to a specific object
No idea what should I do.

emitResult is a non-static member function of IpResolver, I presume. Yet you're calling it without any instance, from a subclass IpResolver::ResolvedInfo. Remember that just because the ResolvedInfo is a subclass, doesn't make it special in any other way. Specifically, if it doesn't hold a reference to the instance of the parent class, it won't work the way you expect it to.
There are two general ways to fix your issue:
You can pass a reference to IpResolver to the ResolvedInfo constructor, and retain the reference in the ResolvedInfo instance:
class IpResolver {
class ResolvedInfo {
IpResolver & q;
public:
ResolvedInfo(IpResolver & q) : q(q) { ... }
static bool load(QTextStream &in) {
ResolvedInfo rf;
while (!in.atEnd())
{
QString line = in.readLine();
QStringList list = line.split(' ');
list[0] = rf.country;
list[1] = rf.ip;
if (!rf.ip.isEmpty())
q.emitResult(rf);
}
}
};
void emitResult(const ResolvedInfo &);
...
};
Or you can make the emitResult a static method:
class IpResolver {
...
static void emitResult(const ResolvedInfo &);
};

Related

What is the proper usage of Q_DECLARE_SMART_POINTER_METATYPE?

I tried to define a function that returns std::shared_ptr<OrderModel> as follows:
Q_DECLARE_SMART_POINTER_METATYPE(std::shared_ptr)
namespace tradeclient {
class OrderModel : public QObject
{
Q_OBJECT
public:
Q_PROPERTY(QString marketId READ marketId CONSTANT)
Q_PROPERTY(quint64 id READ id CONSTANT)
...
};
using OrderPtr = std::shared_ptr<OrderModel>;
class MarketModel : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE tradeclient::OrderPtr createLimitOrder()
{
return m_orders.front();
}
private:
//In my app I initialize OrderModel-s and add them so some container.
std::vector<OrderPtr> m_orders;
};
} //namespace tradeclient
Q_DECLARE_METATYPE(tradeclient::OrderPtr)
qRegisterMetaType<tradeclient::OrderPtr>();
and then call createLimitOrder() from QML:
var order = market.createLimitOrder()
console.log("Limit order type: %1, value: %2, id: %3".arg(typeof(order)).arg(JSON.stringify(order)).arg(order.id))
but with no success, because I can't access order.id and the console output is:
Limit order type: object, value: "", id: undefined
I also tried to define functions like this:
Q_INVOKABLE QVariant createLimitOrder()
{
return QVariant::fromValue(m_orders.front());
}
Q_INVOKABLE QSharedPointer<tradeclient::OrderModel> createLimitOrder()
{
return QSharedPointer<tradeclient::OrderModel>(new OrderModel());
}
but nothing changed.
But at least, QML treats order as a non-empty value and the following QML code:
if (order)
console.log("The order is defined.");
else
console.log("The order is not defined.");
prints:
"The order is defined."
So order is defined, but its properties are not. What did I miss?
Buy the way, the above QML code works correctly if I return naked pointer:
Q_INVOKABLE tradeclient::OrderModel* createLimitOrder()
{
return m_orders.front().get();
}
it prints
Limit order type: object, value: {"objectName":"","marketId":"BTCUSDT","id":0,"side":1,"type":0,"status":0,"price":{"precision":2},"stopPrice":{".....
Does QVariant that wraps std::shared_ptr expose object properties to QML?
EDIT1
As far as I understand, Q_DECLARE_SMART_POINTER_METATYPE is a relatively simple thing, it requires the class template to have operator -> (see ./qtbase/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp):
namespace MyNS {
template<typename T>
class SmartPointer
{
T* pointer;
public:
typedef T element_type;
explicit SmartPointer(T* t = nullptr)
: pointer(t)
{
}
T* operator->() const { return pointer; }
};
}
Q_DECLARE_SMART_POINTER_METATYPE(MyNS::SmartPointer)
so it is reasonable to expect that it behaves like a naked pointer in QML. However, I have concerns that this is one of those cases where they simply did not implement this simple thing well enough.

(Un)Serialize JSON (to)in QObject using nlohmann/json

I want to use the nlohmann/json library to serialize some json to a QObject and vice versa.
The problem I run into is that the parser is trying to use the copy constructor of the QObject, wish is not allowed.
There is something in the documentation regarding this https://github.com/nlohmann/json#how-can-i-use-get-for-non-default-constructiblenon-copyable-types but I can't manage to make it work.
template <>
struct adl_serializer<MyQObject>
{
static MyQObject from_json(const json& j)
{
return {j.get<MyQObject>()}; // call to implicitly-deleted copy constructor of 'MyQObject'
}
static void to_json(json& j, MyQObject t)
{
j = t; // no viable overload '='
}
};
inline void from_json(const json& j, MyQObject& x)
{
x.setXxx(j.at("xxx").get<typeOfXxx>()):
// ...
}
inline void to_json(json& j, const MyQObject& x)
{
j = json::object();
j["xxx"] = x.xxx();
// ...
}
What should I write in the adl_serializer to make it work ?

Why can't access static file with this pointer?

Example I have a program:
class TestStatic
{
private:<br>
static int staticvariable;
public:<br>
TestStatic() {
this->staticvariable = 0;
cout << this->staticvariable;
}
~TestStatic() {}
};
int main() {
TestStatic object;
return 0;
}
why this pointer can't access staticvariable . I don't understand why.
Probably because staticvariable is not bound to this but to your class.
Check out the following answers:
Accessing static class variables in C++?
Undefined reference to static class member
Hope it helps.

QList to QQmlListProperty

I'm trying to pass QList into QML using QQmlListProperty, as official documentation says:
QQmlListProperty::QQmlListProperty(QObject *object, void *data, CountFunction count, AtFunction at)
My code is:
QQmlListProperty<TTimingDriver> TTiming::getDrivers()
{
return QQmlListProperty<TTimingDriver>(this, &m_drivers, &TTiming::count, &TTiming::driverAt);
}
int TTiming::count(QQmlListProperty<TTimingDriver> *property)
{
TTiming * timing = qobject_cast<TTiming *>(property->object);
return timing->m_drivers.count();
}
TTimingDriver * TTiming::driverAt(QQmlListProperty<TTimingDriver> *property, int i)
{
TTiming * timing = qobject_cast<TTiming *>(property->object);
return timing->m_drivers.at(i);
}
But I'm getting an error:
no matching function for call to 'QQmlListProperty<TTimingDriver>::QQmlListProperty(TTiming*, QList<TTimingDriver*>*, int (TTiming::*)(QQmlListProperty<TTimingDriver>*), TTimingDriver* (TTiming::*)(QQmlListProperty<TTimingDriver>*, int))'
return QQmlListProperty<TTimingDriver>(this, &m_drivers, &TTiming::count, &TTiming::driverAt);
I think <ou are mixing two of the QQmlListProperty constructor overloads.
The one that takes the QList<T*> does not need pointers to functions.
So this should be sufficient
QQmlListProperty<TTimingDriver> TTiming::getDrivers()
{
return QQmlListProperty<TTimingDriver>(this, &m_drivers);
}
Assuming that m_drivers is of type QList<TTimingDriver*>

BlackBerry iterate through selectedItems list

So I have FINALLY gotten to the point where I can select multiple items on a ListView:
ListView {
id: lv_stuffs
horizontalAlignment: HorizontalAlignment.Fill
dataModel: _app.personDataModel //REFERENCE 1
multiSelectAction: MultiSelectActionItem {
}
multiSelectHandler {
actions: [
// Add the actions that should appear on the context menu
// when multiple selection mode is enabled
ActionItem {
title: "Search for stuffs"
onTriggered: {
_app.search(lv_stuffs.selectionList());
}
...
And I am sending this selection list through to my search method:
void ApplicationUI::search(const QVariantList &list)
{
alert(QString("%1 items selected").arg(list.length()));
alert(((Person)list.at(0)).firstName);//<---- THIS IS THE PROBLEM
}
I am trying to get the "Person" object out of the GroupedDataModel that originally bound to the item... and I have to say I am more than a little stumped. The person is being added to the personDataModel via a simple insert method in a database class:
personDataModel->insert(person);
and the items are then bound to the ListView in the QML (REFERENCE 1 above). The binding is all fine and the items are visible in the list. What I can't figure out is how to now extract these "Person" objects out of the QVariantList I am sent via the MultiSelectionMethod.
My person class:
Person::Person(QObject *parent) : QObject(parent){}
Person::Person(const QString &id, const QString &firstname, const QString &lastname, QObject *parent)
: QObject(parent)
, m_id(id)
, m_firstName(firstname)
, m_lastName(lastname)
{
}
QString Person::customerID() const
{
return m_id;
}
QString Person::firstName() const
{
return m_firstName;
}
QString Person::lastName() const
{
return m_lastName;
}
void Person::setCustomerID(const QString &newId)
{
if (newId != m_id) {
m_id = newId;
emit customerIDChanged(newId);
}
}
void Person::setFirstName(const QString &newName)
{
if (newName != m_firstName) {
m_firstName = newName;
emit firstNameChanged(newName);
}
}
void Person::setLastName(const QString &newName)
{
if (newName != m_lastName) {
m_lastName = newName;
emit lastNameChanged(newName);
}
}
I have been PAINFULLY following this tutorial here, https://developer.blackberry.com/cascades/documentation/ui/lists/list_view_selection.html, which conveniently stops right where my question begins.
Are you perhaps looking for the value function?
void ApplicationUI::search(const QVariantList &list)
{
alert(QString("%1 items selected").arg(list.length()));
alert(((Person)list.value(0)).firstName);
}
(syntax of the extraction of the firstName value may not be right there, depends on your implementation)
Your Person class will be stored in a QVariant. To accomplish this, Qt has to generate some code specific to your class. It can be done by adding this right after your class definition, in the header file for example: Q_DECLARE_METATYPE(Person). You can read more about this here: http://qt-project.org/doc/qt-4.8/qmetatype.html#Q_DECLARE_METATYPE
Now, to extract the value as a Person object, you can use QVariant::value<T>() (http://qt-project.org/doc/qt-4.8/qvariant.html#value):
alert(list.at(0).value<Person>().firstName());

Resources