QT how to pass Enum to EnumHelper correctly - qt

I have found a helper class for enums (EnumHelper) to convert enums to strings and strings to enums.
I want to use this class in another class (MyEnums) in which I define different enums and want to provide a ToString() and FromString() method for each enum type.
If I try to convert an enum from a third class (Test) I get an error message that I don't understand.
EnumHelper.h
#pragma once
#include <QMetaEnum>
template <typename E>
class EnumHelper
{
public:
EnumHelper();
QString toString(E value);
};
EnumHelper.cpp
#include "EnumHelper.h"
template<typename E>
EnumHelper<E>::EnumHelper()
{
}
template<typename E>
QString EnumHelper<E>::toString(E value)
{
const int retval = static_cast<int>(value);
return QString::fromUtf8(QMetaEnum::fromType<E>().valueToKey(retval));
}
MyEnums.h
#pragma once
#include <QObject>
#include "EnumHelper.h"
class ColorNameEnums
{
Q_GADGET
public:
enum Value {
White,
Grey,
LightGrey,
DarkerGrey,
DarkGrey,
Mint,
DarkMint,
Red,
DarkRed,
Black,
Blue
};
Q_ENUM(Value)
private:
explicit ColorNameEnums();
};
class MyEnums : QObject
{
public:
explicit MyEnums(QObject* parent = nullptr);
QString colorNameToString(ColorNameEnums value);
ColorNameEnums colorNameFromString(QString value);
private:
EnumHelper<ColorNameEnums> m_colorName;
};
MyEnums.cpp
#include "MyEnums.h"
MyEnums::MyEnums(QObject* parent)
{
}
QString MyEnums::colorNameToString(ColorNameEnums value) { return m_colorName.toString(value); }
ColorNameEnums MyEnums::colorNameFromString(QString value) { return m_colorName.fromString(value); }
Test.h
#pragma once
#include <QObject>
#include "MyEnums.h"
class Test : public QObject
{
Q_OBJECT
public:
explicit Test(QObject* parent = nullptr);
private:
MyEnums* m_enums = new MyEnums();
};
Test.cpp
#include "Test.h"
Test::Test(QObject* parent)
{
}
void Test::test()
{
auto xx = m_enums->colorNameToString(ColorNameEnums::White);
}
Error is:
For a conversion of ""ColorNameEnums::Value"" to""ColorNameEnums"" no suitable constructor is available.

Related

QtRemoteObjects autogenerated replica header complaining about undefined vtable

Started using QtRO and generated files inherently complain about vtable:
#ifndef REP_REMOTEEXAMPLE_H
#define REP_REMOTEEXAMPLE_H
// This is an autogenerated file.
// Do not edit this file, any changes made will be lost the next time it is generated.
#include <QtCore/qobject.h>
#include <QtCore/qdatastream.h>
#include <QtCore/qvariant.h>
#include <QtCore/qmetatype.h>
#include <QtRemoteObjects/qremoteobjectnode.h>
#include <QtRemoteObjects/qremoteobjectpendingcall.h>
#include <QtRemoteObjects/qremoteobjectreplica.h>
class remoteExampleReplica : public QRemoteObjectReplica
{
Q_OBJECT
Q_CLASSINFO(QCLASSINFO_REMOTEOBJECT_TYPE, "remoteExample")
Q_CLASSINFO(QCLASSINFO_REMOTEOBJECT_SIGNATURE, "5e40a606abdd95f709878d419edaa735fce25d0d")
public:
remoteExampleReplica() : QRemoteObjectReplica() { initialize(); }
static void registerMetatypes()
{
static bool initialized = false;
if (initialized)
return;
initialized = true;
}
private:
remoteExampleReplica(QRemoteObjectNode *node, const QString &name = QString())
: QRemoteObjectReplica(ConstructWithNode)
{
initializeNode(node, name);
}
void initialize() override
{
remoteExampleReplica::registerMetatypes();
QVariantList properties;
properties.reserve(0);
setProperties(properties);
}
public:
virtual ~remoteExampleReplica() {}
Q_SIGNALS:
void Close(QString a);
void Open(QString b);
public Q_SLOTS:
void onClosed()
{
static int __repc_index = remoteExampleReplica::staticMetaObject.indexOfSlot("onClosed()");
QVariantList __repc_args;
send(QMetaObject::InvokeMetaMethod, __repc_index, __repc_args);
}
void onOpened()
{
static int __repc_index = remoteExampleReplica::staticMetaObject.indexOfSlot("onOpened()");
QVariantList __repc_args;
send(QMetaObject::InvokeMetaMethod, __repc_index, __repc_args);
}
private:
friend class QT_PREPEND_NAMESPACE(QRemoteObjectNode);
};
#if (QT_VERSION < QT_VERSION_CHECK(5, 5, 0))
#endif
QT_BEGIN_NAMESPACE
QT_END_NAMESPACE
#endif // REP_REMOTEEXAMPLE_H
The issue points to the private constructor. I only included the replica header in my code without really using the remote object as a test run. I've read a lot about vtables how they work and when the linker complains about the vtable but in this case, with the private constructor, I'm not sure what the issue is. Am I missing an implementation of the remote object? Did I not generate the files correctly?
.rep:
class remoteExample
{
SIGNAL(Close(QString a));
SIGNAL(Open(QString b));
SLOT(onClosed());
SLOT(onOpened());
};

C++ method defined in .h called in .cpp is not recognized

I am trying to use a method called getName() that is defined in the addPlayer.h file below. The getname() method will be used in the constructor called Player. The error that I get is: 'getName' was not declared in this scope'. How can I fix it?
Thanks for helping.
The addPlayer.h file:
#include "../Source/Player.h"
class addPlayer : public QDialog
{
Q_OBJECT
public:
addPlayer(QWidget *parent = 0);
~addPlayer();
tp::Player* makePlayer();
void addPlayer();
QString getName() const;
inline QString addPlayer::getName() const
{
return (ui.name_lineEdit->text());
}
The addPlayer.cpp file:
#include "addPlayer.h"
#include <QMessageBox>
using namespace tp;
addPlayer::addPlayer(QWidget *parent)
: QDialog(parent)
{
ui.setupUi(this);
QObject::connect(ui.ok_pushButton, SIGNAL(clicked()), this,
SLOT(validatePlayer()));
QObject::connect(ui.dateNaissance_pushButton, SIGNAL(clicked()), this,
SLOT(getDate()));
}
addPlayer::~addPlayer()
{
}
Player* makePlayer()
{
return new Player(getName().toStdString());
}
The constructor is as follows:
class Player: public HumanBeing {
public:
//Constructor
Player(const std::string& p_name);
Player::Player(const std::string& p_name): m_name(p_name)
You haven't properly scoped your definition of makePlayer -- you need to prefix addPlayer:::
Player* addPlayer::makePlayer()
{
return new Player(getName().toStdString());
}

C3767: candidate function(s) not accesible

I have this class:
#pragma once
#ifndef _DEFINES_H_
#include "Defines.h"
#endif
#ifndef _GAMETIME_H_
#include "GameTime.h"
#endif
#ifndef _UTILITIES_H_
#include "Utilities.h"
#endif
#ifndef _GAME_H_
using namespace System;
namespace BSGameFramework
{
public ref class Game
{
public:
Game();
virtual ~Game();
void Run(HINSTANCE instance);
string Title;
int WindowWidth;
int WindowHeight;
protected:
virtual void Initialize();
virtual void LoadContent();
virtual void UnloadContent();
virtual void Update(GameTime^ gameTime);
virtual void Draw(GameTime^ gameTime);
private:
HINSTANCE windowHandler;
HWND window;
DateTime lastTime;
TimeSpan totalGameTime;
D3D_DRIVER_TYPE driverType_;
D3D_FEATURE_LEVEL featureLevel_;
ID3D11Device* d3dDevice_;
ID3D11DeviceContext* d3dContext_;
IDXGISwapChain* swapChain_;
ID3D11RenderTargetView* backBufferTarget_;
void Shutdown();
};
}
#define _GAME_H_
#endif
and this is its child:
#pragma once
using namespace BSGameFramework;
public ref class MyGame : Game
{
public:
MyGame()
{
}
};
Then when on my Main I call my Run function:
#include <Windows.h>
#include "MyGame.h"
using namespace BSGameFramework;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
MyGame ^game = gcnew MyGame();
game->Run(hInstance); // Here the error
}
I get this error:
Error 1 error C3767: 'BSGameFramework::Game::Run': candidate function(s) not accessible
C:\Users\Nicola\Desktop\directx prove\BSGameFramework\FrameworkTestCpp\Main.cpp 10 1 FrameworkTestCpp
I've tried to remove the HINSTANCE from Run parameters and all is working fine, but I need it so somebody can explain me why I'm getting this error and how can I solve? Thanks in advance!
I have solved in this way:
inline void Game::Run(IntPtr instance)
{
windowHandler = (HINSTANCE)instance.ToPointer();
// other code
}
now I'm passing an IntPtr that is not a native type, so on main function I have this:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
MyGame ^game = gcnew MyGame();
IntPtr instance(hInstance);
game->Run(instance);
}

Q_DECLARE_METATYPE doesn't work at all

I'm trying to use custom classes in QAbstractListModel, and the Q_DECLARE_METATYPE doesn't work at all!
To test where the problem is, I've simplified the code as the following:
#include <QMetaType>
#include <QVariant>
#include <QDebug>
typedef int x;
Q_DECLARE_METATYPE(x)
void main() {
QVariant v;
qDebug() << v.canConvert<x>();
}
and the output is still false!
btw, the code I want to implement is like:
namespace ns{
class a {
public:
a(); //default constructor
a(const a&); //copy constructor
~a();
}
}
Q_DECALRE_METATYPE(ns::a);
and when I try to reimplement QAbstractListModel::data like this:
QList<ns::s> list; //this is actually a member field of the custom model.
QVariant MyListModel::data(const QModelIndex& index, int role) const {
Q_UNUSED(role)
return list.at(index.row());
}
the compiler will report and error like:
cannot convert const ns::a to QVariant::Type
Your example is overly simplified as the docs quite clearly state that the class/struct being passed to Q_DECLARE_METATYPE must have a default constructor, a copy constructor and a public destructor: http://qt-project.org/doc/qt-5.0/qtcore/qmetatype.html#Q_DECLARE_METATYPE
That being said, here's a pretty simple example that shows Q_DECLARE_METATYPE working:
#include <QMetaType>
#include <QVariant>
#include <QDebug>
namespace MyNS {
class MyClass {
public:
MyClass() : value(0) { }
MyClass(int value) : value(value) { }
MyClass(const MyClass &other) { value = other.value; }
~MyClass() { }
int getValue() const { return value; }
private:
int value;
};
};
Q_DECLARE_METATYPE(MyNS::MyClass);
int main(int argc, char *argv[])
{
MyNS::MyClass m(15);
QVariant v = QVariant::fromValue(m);
qDebug() << v.canConvert<MyNS::MyClass>();
qDebug() << v.value<MyNS::MyClass>().getValue();
}

QOBJECT macro declared

I have declared QOBJECT macro but still its calling the function without passing the QObject object
Here is my code
keyusermanagertest.cpp
#define private public
#define protected public
#include "keyusermanagertest.h"
#include "storageusermanager.h"
#include "keyusermanager.h"
#include "alkuser.h"
#undef protected
#undef private
#include <QDebug>
#include <QtTest/QtTest>
QTEST_MAIN(KeyUserManagerTest)
void KeyUserManagerTest::init()
{
}
void KeyUserManagerTest::cleanup()
{
}
void KeyUserManagerTest::test_initialization()
{
// Already tested under BackendTest::test_initialization()
}
void KeyUserManagerTest::settersAndGetters()
{
AlkUser userInfo;
QString user="Puneet Goyal";
StorageUserManager* storageuser=new StorageUserManager();
KeyUserManager* keyuser=new KeyUserManager(storageuser);
keyuser->updateUserData(user,userInfo);
qDebug()<<"UPDATION DONE!!!!";
// Now setting the rest of the details for user Puneet Goyal using AlkUser Object
userInfo.setName("Puneet");
userInfo.setContact("21897121");
userInfo.setType("savings");
userInfo.setAccount("123456789");
userInfo.setAmount("100000");
// Now retrieving all the user details using KeyUserManager Object
QVariant vari=keyuser->getUserInfo("Puneet Goyal");
}
keyusermanagertest.h
#ifndef KEYUSERMANAGERTEST_H
#define KEYUSERMANAGERTEST_H
#include <QtCore/QObject>
class KeyUserManager;
class KeyUserManagerTest : public QObject
{
Q_OBJECT
private slots:
void init();
void cleanup();
void test_initialization();
void settersAndGetters();
};
#endif
Its compile output is as follows"
/home/puneet/puneet/office/alkimia/payment/backend/keyusermanagertest.cpp: In member function ‘void KeyUserManagerTest::settersAndGetters()’:
/home/puneet/puneet/office/alkimia/payment/backend/keyusermanagertest.cpp:52: error: no matching function for call to ‘StorageUserManager::StorageUserManager()’
/home/puneet/puneet/office/alkimia/payment/backend/storageusermanager.h:41: note: candidates are: StorageUserManager::StorageUserManager(QObject*)
/home/puneet/puneet/office/alkimia/payment/backend/storageusermanager.h:37: note: StorageUserManager::StorageUserManager(const StorageUserManager&)
/home/puneet/puneet/office/alkimia/payment/backend/keyusermanagertest.cpp:53: error: no matching function for call to ‘KeyUserManager::KeyUserManager(StorageUserManager*&)’
/home/puneet/puneet/office/alkimia/payment/backend/keyusermanager.h:44: note: candidates are: KeyUserManager::KeyUserManager(StorageUserManager*, QObject*)
/home/puneet/puneet/office/alkimia/payment/backend/keyusermanager.h:41: note: KeyUserManager::KeyUserManager(const KeyUserManager&)
Thanks
Add constructor to your KeyUserManagerTest -
in header add
KeyUserManagerTest (QObject* parent=0);
and in cpp
KeyUserManagerTest::KeyUserManagerTest(QObject* parent):QObject(parent){};
QOBJECT macro does not create constructor for you!

Resources