Menu

Creating custom objects on c++ side

Help
Anton
2015-03-18
2015-03-19
  • Anton

    Anton - 2015-03-18

    Hi! What is the way to create custom objects and passing them to python scripts?
    In examples I found PyCustomMetaTypeExample, but I need something like this:

    //....
    // Custom object created in c++
    //
        CustomObjectWrapper* custom = new CustomObjectWrapper();
    
        qRegisterMetaType<CustomObject>("CustomObject");
    
        PythonQt::self()->registerCPPClass(
            "CustomObject","","example",     
            PythonQtCreateObject<CustomObjectWrapper>);
    
    // Here I want to pass "custom" to python script
    //
        mainModule.addObject("custom", custom );
    
        mainModule.evalFile("GettingStarted2.py");
    
    
    // And then receive custom object with python's script changes, 
    // I don't know how access custom 
    //    qDebug() << "Custom"   << custom->firstName; ??? 
    
     
  • Anton

    Anton - 2015-03-18

    Just try this code, it don't has result too.
    In header:

    class CustomObject2 : public QObject {
      Q_OBJECT
    
    public:
      QString _firstName;
      QString _lastName;
    
      QString firstName() { return _firstName; }
      QString lastName() { return _lastName; }
    
      void setFirstName(const QString& name) { _firstName = name; }
      void setLastName(const QString& name) { _lastName = name; }
    };
    

    In main.cpp:

        QCoreApplication a(argc, argv);
        PythonQt::init();
        PythonQtObjectPtr 
                 mainModule =  PythonQt::self()->getMainModule();
    
        CustomObject2* custom = new CustomObject2();
    
        PythonQt::self()->registerClass( &CustomObject2::staticMetaObject, "example" );
    
        mainModule.addObject("custom", custom );
        mainModule.evalFile("GettingStarted2.py");
    
        QVariant result = mainModule.evalScript("custom.firstName()", Py_eval_input);
    
        qDebug() << "Finished" << custom->firstName() << result; 
    

    In GettingStarted2.py:

    from PythonQt.example import CustomObject2
    
    # set a name
    custom.setFirstName("Mike")
    custom.setLastName("Michels")
    

    Output:

    Finished "" QVariant(, )

     

    Last edit: Anton 2015-03-18
  • Florian Link

    Florian Link - 2015-03-18

    In you second example, you need to place the methods that should be scriptable into a

    public slots:

    section. Alternatively, you can add a Q_INVOKABLE macro in front of each method that should be scriptable, but using slots is more common.

    Have a closer look at the PythonQt examples, all your questions should be answered by the examples.

     
    • Anton

      Anton - 2015-03-19

      Fine! Thank You very much, Florian!

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.