Objective c with Qt side by side



Q: main.cpp or main.mm?
A: if the class is following cpp format and the .h is following c++ then main.cpp or main.mm can be used.
if the .h file is following objective-c then main.cpp should be renamed to main.mm

Remarks: 
-with .mm the simulator may not work and gives you an error, try it on a real device.
-NSLog doesn't show in the console if the app is executed from Qt Creator. Open the project in XCode and then the NSLog messages will show


TestNS.mm

 #include "TestNS.h"
#include <QDebug>
#include<Foundation/Foundation.h>

TestNS::TestNS(QObject *parent) : QObject(parent){
}

void TestNS::test(){
    NSLog(@"\n\n\n***\n***\n***\nThis is a test");
}
TestNS.h

#ifndef TESTNS_H
#define TESTNS_H
#include <QObject>
class TestNS : public QObject
{
    Q_OBJECT
public:
    explicit TestNS(QObject *parent = 0);
    Q_INVOKABLE void test();
signals:

public slots:
};

#endif


main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "TestNS.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    qmlRegisterType<TestNS>("TestNS.com", 1, 0, "TestNS");
    QQmlApplicationEngine engine;
    TestNS * testns = new TestNS();
    testns->test();
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}

main.qml

import QtQuick 2.0
import TestNS.com 1.0

Item {
    Rectangle{
        radius: 5
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter
        color: "green"
        width: parent.width/2
        height: parent.height/2
        MouseArea{
            anchors.fill: parent
            onClicked:{
                console.debug("clicked")
                testns.test()
            }
        }
    }
    TestNS{
        id: testns
    }
}

Special Thanks to Mike Krus's video: see https://www.youtube.com/watch?v=8A7DPUwIcDg

Comments

Popular Posts