Qt for Python/Porting guide: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
Line 35: Line 35:
To explain this better, let's try to port the existing Qt C++ application to Python. [https://code.qt.io/cgit/qt/qtbase.git/tree/examples/sql/books?h=5.12.2 The books SQL example] seems ideal for this, as we could avoid writing UI-specific code in Python and use the ''.ui'' file, which describes the application's UI.
To explain this better, let's try to port the existing Qt C++ application to Python. [https://code.qt.io/cgit/qt/qtbase.git/tree/examples/sql/books?h=5.12.2 The books SQL example] seems ideal for this, as we could avoid writing UI-specific code in Python and use the ''.ui'' file, which describes the application's UI.


=== initDb.h -> initDb.py ===
=== initDb.h -> createdb.py ===


To begin with let's try to port the C++ code that creates an sqllite database and tables, and adds data to them. In this case, all C++ code related to this lives in the ''initdb.h''. The code in this header file is divided into these following parts:
To begin with let's try to port the C++ code that creates an sqllite database and tables, and adds data to them. In this case, all C++ code related to this lives in the ''initdb.h''. The code in this header file is divided into these following parts:


* initDb - Creates a db and the necessary tables
* init_db - Creates a db and the necessary tables
* addBooks - Adds book info. to the **books** table.  
* addBooks - Adds book info. to the **books** table.  
* addAuthor - Adds author info. to the **authors** table.
* addAuthor - Adds author info. to the **authors** table.
* addGenre - Adds genre info. to the **genres** table.
* addGenre - Adds genre info. to the **genres** table.


To start with, create the ''initdb.py'' and add the following import statements at the beginning:
To start with, create the ''createdb.py'' and add the following import statements at the beginning:
<syntaxhighlight lang="python" line="line">
<syntaxhighlight lang="python" line="line">
import sqlite3
from PySide2.QtSql import QSqlDatabase, QSqlError, QSqlQuery
from sqlite3 import Error
from datetime import datetime
from datetime import datetime


</syntaxhighlight>
</syntaxhighlight>
These are all the imports we need to get our database in place using the Python-specific packages for database interaction.
These are all the imports we need to get our database in place.


Let's look at at the code for the ''initDb'' C++ method and port it to an equivalent in Python:
Let's look at at the code for the ''initDb'' C++ method and port it to an equivalent function in Python:
{|
{|
! style="margin-top: 0px;"| C++
! style="margin-top: 0px;"| C++
Line 112: Line 111:
</syntaxhighlight>
</syntaxhighlight>
|<syntaxhighlight lang="python" style="font-size: 12px;font-family: DROID SANS MONO">
|<syntaxhighlight lang="python" style="font-size: 12px;font-family: DROID SANS MONO">
def initDb(db_file):
def init_db():
     """Creates an SQLite db and adds data to it"""
     db = QSqlDatabase.addDatabase("QSQLITE")
    try:
    db.setDatabaseName(":memory:")
        conn = sqlite3.connect(db_file)
        cur =  conn.cursor()
        sqlScript = """
            create table if not exists books(
                id integer primary key,
                title varchar,
                author integer,
                genre integer,
                year integer,
                rating integer
            );
           
            create table if not exists authors(
                id integer primary key,
                name varchar,
                birthdate date
            );
           
            create table if not exists genres(
                id integer primary key,
                name varchar
            );           
            """
        cur.executescript(sqlScript)
        #Adding authors
        asimovId = addAuthor(cur, u"Isaac Asimov", datetime(1920, 2, 1))
        greeneId = addAuthor(cur, u"Graham Greene", datetime(1904, 10, 2))
        pratchettId = addAuthor(cur, u"Terry Pratchett", datetime(1948, 4, 28))
       
        #Adding genres
        sfiction = addGenre(cur, u"Science Fiction")
        fiction = addGenre(cur, u"Fiction")
        fantasy = addGenre(cur, u"Fantasy")
       
        #Adding books
        addBook(cur, u"Foundation", 1951, asimovId, sfiction, 3);
        addBook(cur, u"Foundation and Empire", 1952, asimovId, sfiction, 4);
        addBook(cur, u"Second Foundation", 1953, asimovId, sfiction, 3);
        addBook(cur, u"Foundation's Edge", 1982, asimovId, sfiction, 3);
        addBook(cur, u"Foundation and Earth", 1986, asimovId, sfiction, 4);
        addBook(cur, u"Prelude to Foundation", 1988, asimovId, sfiction, 3);
        addBook(cur, u"Forward the Foundation", 1993, asimovId, sfiction, 3);
        addBook(cur, u"The Power and the Glory", 1940, greeneId, fiction, 4);
        addBook(cur, u"The Third Man", 1950, greeneId, fiction, 5);
        addBook(cur, u"Our Man in Havana", 1958, greeneId, fiction, 4);
        addBook(cur, u"Guards! Guards!", 1989, pratchettId, fantasy, 3);
        addBook(cur, u"Night Watch", 2002, pratchettId, fantasy, 3);
        addBook(cur, u"Going Postal", 2004, pratchettId, fantasy, 3);


     except Error as e:
     if not db.open():
         print(e)
        return db.lastError()
     finally:
 
         conn.close()
    tables = db.tables()
    for table in tables:
        if table == "books" and table == "authors":
            return QSqlError()
 
    q = QSqlQuery()
    if not q.exec_("create table books(id integer primary key, title varchar, author integer, "
            "genre integer, year integer, rating integer)"):
        return q.lastError()
    if not q.exec_("create table authors(id integer primary key, name varchar, birthdate date)"):
        return q.lastError()
    if not q.exec_("create table genres(id integer primary key, name varchar)"):
        return q.lastError()
 
    if not q.prepare("insert into authors(name, birthdate) values(?, ?)"):
        return q.lastError()
    asimovId = add_author(q, "Isaac Asimov", datetime(1920, 2, 1))
    greeneId = add_author(q, "Graham Greene", datetime(1904, 10, 2))
    pratchettId = add_author(q, "Terry Pratchett", datetime(1948, 4, 28))
 
    if not q.prepare("insert into genres(name) values(?)"):
         return q.lastError()
    sfiction = add_genre(q, "Science Fiction")
    fiction = add_genre(q, "Fiction")
    fantasy = add_genre(q, "Fantasy")
 
     if not q.prepare("insert into books(title, year, author, genre, rating) "
            "values(?, ?, ?, ?, ?)"):
         return q.lastError()
    add_book(q, "Foundation", 1951, asimovId, sfiction, 3)
    add_book(q, "Foundation and Empire", 1952, asimovId, sfiction, 4)
    add_book(q, "Second Foundation", 1953, asimovId, sfiction, 3)
    add_book(q, "Foundation's Edge", 1982, asimovId, sfiction, 3)
    add_book(q, "Foundation and Earth", 1986, asimovId, sfiction, 4)
    add_book(q, "Prelude to Foundation", 1988, asimovId, sfiction, 3)
    add_book(q, "Forward the Foundation", 1993, asimovId, sfiction, 3)
    add_book(q, "The Power and the Glory", 1940, greeneId, fiction, 4)
    add_book(q, "The Third Man", 1950, greeneId, fiction, 5)
    add_book(q, "Our Man in Havana", 1958, greeneId, fiction, 4)
    add_book(q, "Guards! Guards!", 1989, pratchettId, fantasy, 3)
    add_book(q, "Night Watch", 2002, pratchettId, fantasy, 3)
    add_book(q, "Going Postal", 2004, pratchettId, fantasy, 3)
 
    return QSqlError()
</syntaxhighlight>
</syntaxhighlight>
|}
|}
Line 173: Line 167:
Notice that the Python version of the ''initDb'' function does not use anything specific to Qt for setting up the database.
Notice that the Python version of the ''initDb'' function does not use anything specific to Qt for setting up the database.


* The ''initDb'' calls the ''addAuthor'', ''addGenre'', and ''addBook'' functions to append data to the tables. Let's try porting these functions to Python.
* The ''init_db'' calls the ''addAuthor'', ''addGenre'', and ''addBook'' functions to append data to the tables. Let's try porting these functions to Python.


{|
{|
Line 207: Line 201:
</syntaxhighlight>
</syntaxhighlight>
|<syntaxhighlight lang="python" style="font-size: 12px;font-family: DROID SANS MONO">
|<syntaxhighlight lang="python" style="font-size: 12px;font-family: DROID SANS MONO">
def addBook(cur, title, year, authorId, genreId, rating):
def add_book(q, title, year, authorId, genreId, rating):
     """Adds a book to the books table"""
     q.addBindValue(title)
     insertBookInfo = "insert into books(title,author,genre,year,rating) values(?,?,?,?,?)"               
     q.addBindValue(year)
           
    q.addBindValue(authorId)
     try:
    q.addBindValue(genreId)
        cur.execute(insertBookInfo,(title, authorId , genreId , year , rating))
    q.addBindValue(rating)
     except Error as e:
    q.exec_()
        print(e)
 
 
def add_genre(q, name):
    q.addBindValue(name)
     q.exec_()
    return q.lastInsertId()
 
 
def add_author(q, name, birthdate):
    q.addBindValue(name)
    q.addBindValue(birthdate)
     q.exec_()
    return q.lastInsertId()


def addAuthor(cur, name, dob):
    """Adds a author to the authors table"""
    insertAuthorInfo = "insert into authors(name, birthdate) values(?,?)"
    try:
        cur.execute(insertAuthorInfo,(name,dob))
        #cur.commit()
        cur.execute("select id from authors where name=:name", {"name": name})
        id = cur.fetchone()[0]
        return id
    except Error as e:
        print(e)


def addGenre(cur, genreName):
    """Adds a genre to the genres table"""
    insertGenreInfo = "insert into genres(name) values(?)"
    try:
        cur.execute(insertGenreInfo,(genreName,))
        cur.execute("select id from genres where name=:name", {"name": genreName})
        id = cur.fetchone()[0]
        return id
    except Error as e:
        print(e)
</syntaxhighlight>
</syntaxhighlight>
|}
|}

Revision as of 10:49, 8 May 2019

Qt for Python is an offering that enable developing Qt applications in a pythonic way. I guess, that didn't go well with most you who have been using Python for years! Let's try to rephrase, Qt for Python is a binding for Qt, to enable Python application development using Qt. Ah..that sounds about right! Isn't it? So, the idea behind Qt for Python is probably clear now. Let's see what does it take to port an existing Qt C++ application to Python. Before we start digging deeper into this topic, let's ensure that we have all the prerequisites met. For example, installing either Python2 or Python3, and so on. Wait a minute, isn't this information outlined in the Getting started section of the documentation. In that case, let's dive straight into the topic.

Assuming that you have required environment to develop Python applications using PySide2(Qt for Python), let's get started. But, we need a C++-based Qt application to port. Let's pick a Qt example that has the .ui XML file, defining the application's UI. That way, we avoid the need to write the code to create a UI. Wait a minute, isn't that the reason why Qt was developed in the first place?

Basic differences

Before we get started, let's familiarize ourselves with some of the basic differences between the Qt C++ and Python code:

  • C++ being an object-oriented programming language, we reuse code that is already defined in another file, using the "#include" statements at the beginning. Similarly, we use "import" statements in Python to access packages and classes. Here are is the classic Hello World example using the Python bindings for Qt (PySide2):
import sys
from PySide2.QtWidgets import QApplication, QLabel
                                                     
if __name__ == "__main__":
    app = QApplication(sys.argv)
    label = QLabel("Hello World")
    label.show()
    sys.exit(app.exec_())

Notice, that the application code begins with a couple of import statements to include the sys, and QApplication and QLabel classes from PySide2.QtWidgets.

  • Similar to a C++ application, the Python application also needs an entry point. Not because a Python application must have one, but because it is a good practice to have one. In the Hello World example code that we looked at earlier, you can see that the entry point is defined by the following line:
if __name__ == "__main__":
   #...
  • Qt provides classes that are meant to manage the application-specific requirements depending whether the application is a console-only, GUI with QtWidgets, or GUI without QtWidgets. These classes load necessary plugins, such as the GUI libraries required by a GUI application.
  • Q_PROPERTY macros are used in Qt to add a public member variable with a getter and setter functions. Python alternative for this is the @property decorator before the getter and setter function definitions.
  • Qt offers a unique way of callback mechanism, where a signal is emitted to notify the occurrence of a event, so that slots connected to this signal can react to it. Python alternative for this is to identify
  • In C++, we use the keyword, this, to refer to the current object. In a Python context, it is self that offers something similar.

Porting tutorial

To explain this better, let's try to port the existing Qt C++ application to Python. The books SQL example seems ideal for this, as we could avoid writing UI-specific code in Python and use the .ui file, which describes the application's UI.

initDb.h -> createdb.py

To begin with let's try to port the C++ code that creates an sqllite database and tables, and adds data to them. In this case, all C++ code related to this lives in the initdb.h. The code in this header file is divided into these following parts:

  • init_db - Creates a db and the necessary tables
  • addBooks - Adds book info. to the **books** table.
  • addAuthor - Adds author info. to the **authors** table.
  • addGenre - Adds genre info. to the **genres** table.

To start with, create the createdb.py and add the following import statements at the beginning:

from PySide2.QtSql import QSqlDatabase, QSqlError, QSqlQuery
from datetime import datetime

These are all the imports we need to get our database in place.

Let's look at at the code for the initDb C++ method and port it to an equivalent function in Python:

C++ Python
QSqlError initDb()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");

    if (!db.open())
        return db.lastError();

    QStringList tables = db.tables();
    if (tables.contains("books", Qt::CaseInsensitive)
        && tables.contains("authors", Qt::CaseInsensitive))
        return QSqlError();

    QSqlQuery q;
    if (!q.exec(QLatin1String("create table books(id integer primary key, title varchar, author integer, genre integer, year integer, rating integer)")))
        return q.lastError();
    if (!q.exec(QLatin1String("create table authors(id integer primary key, name varchar, birthdate date)")))
        return q.lastError();
    if (!q.exec(QLatin1String("create table genres(id integer primary key, name varchar)")))
        return q.lastError();

    if (!q.prepare(QLatin1String("insert into authors(name, birthdate) values(?, ?)")))
        return q.lastError();
    QVariant asimovId = addAuthor(q, QLatin1String("Isaac Asimov"), QDate(1920, 2, 1));
    QVariant greeneId = addAuthor(q, QLatin1String("Graham Greene"), QDate(1904, 10, 2));
    QVariant pratchettId = addAuthor(q, QLatin1String("Terry Pratchett"), QDate(1948, 4, 28));

    if (!q.prepare(QLatin1String("insert into genres(name) values(?)")))
        return q.lastError();
    QVariant sfiction = addGenre(q, QLatin1String("Science Fiction"));
    QVariant fiction = addGenre(q, QLatin1String("Fiction"));
    QVariant fantasy = addGenre(q, QLatin1String("Fantasy"));

    if (!q.prepare(QLatin1String("insert into books(title, year, author, genre, rating) values(?, ?, ?, ?, ?)")))
        return q.lastError();
    addBook(q, QLatin1String("Foundation"), 1951, asimovId, sfiction, 3);
    addBook(q, QLatin1String("Foundation and Empire"), 1952, asimovId, sfiction, 4);
    addBook(q, QLatin1String("Second Foundation"), 1953, asimovId, sfiction, 3);
    addBook(q, QLatin1String("Foundation's Edge"), 1982, asimovId, sfiction, 3);
    addBook(q, QLatin1String("Foundation and Earth"), 1986, asimovId, sfiction, 4);
    addBook(q, QLatin1String("Prelude to Foundation"), 1988, asimovId, sfiction, 3);
    addBook(q, QLatin1String("Forward the Foundation"), 1993, asimovId, sfiction, 3);
    addBook(q, QLatin1String("The Power and the Glory"), 1940, greeneId, fiction, 4);
    addBook(q, QLatin1String("The Third Man"), 1950, greeneId, fiction, 5);
    addBook(q, QLatin1String("Our Man in Havana"), 1958, greeneId, fiction, 4);
    addBook(q, QLatin1String("Guards! Guards!"), 1989, pratchettId, fantasy, 3);
    addBook(q, QLatin1String("Night Watch"), 2002, pratchettId, fantasy, 3);
    addBook(q, QLatin1String("Going Postal"), 2004, pratchettId, fantasy, 3);

    return QSqlError();
}
def init_db():
    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(":memory:")

    if not db.open():
        return db.lastError()

    tables = db.tables()
    for table in tables:
        if table == "books" and table == "authors":
            return QSqlError()

    q = QSqlQuery()
    if not q.exec_("create table books(id integer primary key, title varchar, author integer, "
            "genre integer, year integer, rating integer)"):
        return q.lastError()
    if not q.exec_("create table authors(id integer primary key, name varchar, birthdate date)"):
        return q.lastError()
    if not q.exec_("create table genres(id integer primary key, name varchar)"):
        return q.lastError()

    if not q.prepare("insert into authors(name, birthdate) values(?, ?)"):
        return q.lastError()
    asimovId = add_author(q, "Isaac Asimov", datetime(1920, 2, 1))
    greeneId = add_author(q, "Graham Greene", datetime(1904, 10, 2))
    pratchettId = add_author(q, "Terry Pratchett", datetime(1948, 4, 28))

    if not q.prepare("insert into genres(name) values(?)"):
        return q.lastError()
    sfiction = add_genre(q, "Science Fiction")
    fiction = add_genre(q, "Fiction")
    fantasy = add_genre(q, "Fantasy")

    if not q.prepare("insert into books(title, year, author, genre, rating) "
            "values(?, ?, ?, ?, ?)"):
        return q.lastError()
    add_book(q, "Foundation", 1951, asimovId, sfiction, 3)
    add_book(q, "Foundation and Empire", 1952, asimovId, sfiction, 4)
    add_book(q, "Second Foundation", 1953, asimovId, sfiction, 3)
    add_book(q, "Foundation's Edge", 1982, asimovId, sfiction, 3)
    add_book(q, "Foundation and Earth", 1986, asimovId, sfiction, 4)
    add_book(q, "Prelude to Foundation", 1988, asimovId, sfiction, 3)
    add_book(q, "Forward the Foundation", 1993, asimovId, sfiction, 3)
    add_book(q, "The Power and the Glory", 1940, greeneId, fiction, 4)
    add_book(q, "The Third Man", 1950, greeneId, fiction, 5)
    add_book(q, "Our Man in Havana", 1958, greeneId, fiction, 4)
    add_book(q, "Guards! Guards!", 1989, pratchettId, fantasy, 3)
    add_book(q, "Night Watch", 2002, pratchettId, fantasy, 3)
    add_book(q, "Going Postal", 2004, pratchettId, fantasy, 3)

    return QSqlError()

Notice that the Python version of the initDb function does not use anything specific to Qt for setting up the database.

  • The init_db calls the addAuthor, addGenre, and addBook functions to append data to the tables. Let's try porting these functions to Python.
C++ Python
void addBook(QSqlQuery &q, const QString &title, int year, const QVariant &authorId,
             const QVariant &genreId, int rating)
{
    q.addBindValue(title);
    q.addBindValue(year);
    q.addBindValue(authorId);
    q.addBindValue(genreId);
    q.addBindValue(rating);
    q.exec();
}

QVariant addGenre(QSqlQuery &q, const QString &name)
{
    q.addBindValue(name);
    q.exec();
    return q.lastInsertId();
}

QVariant addAuthor(QSqlQuery &q, const QString &name, const QDate &birthdate)
{
    q.addBindValue(name);
    q.addBindValue(birthdate);
    q.exec();
    return q.lastInsertId();
}
def add_book(q, title, year, authorId, genreId, rating):
    q.addBindValue(title)
    q.addBindValue(year)
    q.addBindValue(authorId)
    q.addBindValue(genreId)
    q.addBindValue(rating)
    q.exec_()


def add_genre(q, name):
    q.addBindValue(name)
    q.exec_()
    return q.lastInsertId()


def add_author(q, name, birthdate):
    q.addBindValue(name)
    q.addBindValue(birthdate)
    q.exec_()
    return q.lastInsertId()