Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Calling C++ functions from QML doesn't work



  • Hey I've tried to call a c++ function from QML.

    let say i have following class

    ```
    
    class ProxySettings : public QObject
    	{
    	public:
    		explicit ProxySettings(QObject* parent = nullptr);
    		virtual ~ProxySettings();
    
    		Q_INVOKABLE QString getHttp()
    		{
    			return "Test Ogden port";
    		}
    
    public slots:
    		void help()
    		{
    			std::cout << "put slei abc" << std::endl;
    		}
    	};
    
    
    
    which i register the following way:
    	qmlRegisterType<ProxySettings>("remotedui.qt.proxysettings", 1, 0, "ProxySettingsNative");
    
    
    
    
    and I try to use it in QML:
    
    import QtQuick 2.9
    import QtQuick.Window 2.0
    import QtQuick.Controls 2.0
    import remotedui.qt.proxysettings 1.0
    
    Window
    {
    	property alias qProxySettings : cpp_qProxySettings
    	
    	ProxySettingsNative
    	{
    		id: cpp_qProxySettings
    	}
    
    	property var http: getHttp();
    
    
    	function reset()
    	{
    		cpp_qProxySettings.help();
    		http = cpp_qProxySettings.getHttp()
    	}
    
    }
    
    

    But I always geht following error:
    qrc:/ui/ProxySettings.qml:31: TypeError: Property 'help' of object QObject(0x180550d8) is not a function

    same with getHttp.

    The ProxySettings get created correctly(when trying to debug through the cpp class) and is the QObject pointer from the error log is the same.

    am i missing something?


  • Moderators

    @Slei
    two things come to my mind,

    add the Q_Object macro, its missing in your code example
    and the help function is missing the Q_INVOKABLE macro



  • uff, i did indeed miss the Q_OBJECT macro and didn't see it ._. adding the missing Q_OBJECt did the job thanks


Log in to reply