Time for action – writing a Qt wrapper for embedding Python

As the first task, we will implement the last program using an object-oriented API. Create a new console project and add the following class to it:

#include <Python.h>
#include <QObject>
#include <QString>
class QtPython : public QObject {
  Q_OBJECT
public:
  QtPython(const char *progName, QObject *parent = 0) : QObject(parent) { 
    if(progName != 0) {
        wchar_t buf[strlen(progName+1)];
        mbstowcs(buf, progName, strlen(progName));
        Py_SetProgramName(buf);
    }
    Py_InitializeEx(0);
  }
  ~QtPython() { Py_Finalize(); }
  void run(const QString &program) {
    PyRun_SimpleString(qPrintable(program));
  }
};

Then, add a main() function as shown in the following snippet:

#include "qtpython.h" int main(int argc, char **argv) ...

Get Game Programming Using Qt now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.