Chapter 3: Port bookdwindow.cpp to bookwindow.py

After the bookdelegate, port the C++ code for the BookWindow class. It offers a QMainWindow, containing a QTableView to present the books data, and a Details section with a set of input fields to edit the selected row in the table. To begin with, create the bookwindow.py and add the following imports to it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

from __future__ import print_function, absolute_import

from PySide2.QtWidgets import (QAction, QAbstractItemView, qApp, QDataWidgetMapper,
    QHeaderView, QMainWindow, QMessageBox)
from PySide2.QtGui import QKeySequence
from PySide2.QtSql import (QSqlRelation, QSqlRelationalTableModel, QSqlTableModel,
    QSqlError)
from PySide2.QtCore import QAbstractItemModel, QObject, QSize, Qt, Slot
import createdb
from ui_bookwindow import Ui_BookWindow
from bookdelegate import BookDelegate


Note

The imports include the BookDelegate you ported earlier and the Ui_BookWindow. The pyside-uic tool generates the ui_bookwindow Python code based on the bookwindow.ui XML file.

To generate this Python code, run the following command on the prompt:

pyside2-uic bookwindow.ui > ui_bookwindow.py

Try porting the remaining code now. To begin with, here is how both the versions of the constructor code looks:

C++ version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
** $QT_END_LICENSE$
**
****************************************************************************/

#include "bookwindow.h"
#include "bookdelegate.h"
#include "initdb.h"

#include <QtSql>

BookWindow::BookWindow()
{
    ui.setupUi(this);

    if (!QSqlDatabase::drivers().contains("QSQLITE"))
        QMessageBox::critical(
                    this,
                    "Unable to load database",
                    "This demo needs the SQLITE driver"
                    );

    // Initialize the database:
    QSqlError err = initDb();
    if (err.type() != QSqlError::NoError) {
        showError(err);
        return;
    }

    // Create the data model:
    model = new QSqlRelationalTableModel(ui.bookTable);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setTable("books");

    // Remember the indexes of the columns:
    authorIdx = model->fieldIndex("author");
    genreIdx = model->fieldIndex("genre");

    // Set the relations to the other database tables:
    model->setRelation(authorIdx, QSqlRelation("authors", "id", "name"));
    model->setRelation(genreIdx, QSqlRelation("genres", "id", "name"));

    // Set the localized header captions:
    model->setHeaderData(authorIdx, Qt::Horizontal, tr("Author Name"));
    model->setHeaderData(genreIdx, Qt::Horizontal, tr("Genre"));
    model->setHeaderData(model->fieldIndex("title"),
                         Qt::Horizontal, tr("Title"));
    model->setHeaderData(model->fieldIndex("year"), Qt::Horizontal, tr("Year"));
    model->setHeaderData(model->fieldIndex("rating"),
                         Qt::Horizontal, tr("Rating"));

    // Populate the model:
    if (!model->select()) {
        showError(model->lastError());
        return;
    }

    // Set the model and hide the ID column:
    ui.bookTable->setModel(model);
    ui.bookTable->setItemDelegate(new BookDelegate(ui.bookTable));
    ui.bookTable->setColumnHidden(model->fieldIndex("id"), true);
    ui.bookTable->setSelectionMode(QAbstractItemView::SingleSelection);

    // Initialize the Author combo box:
    ui.authorEdit->setModel(model->relationModel(authorIdx));
    ui.authorEdit->setModelColumn(
                model->relationModel(authorIdx)->fieldIndex("name"));

    ui.genreEdit->setModel(model->relationModel(genreIdx));
    ui.genreEdit->setModelColumn(

Python version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

class BookWindow(QMainWindow, Ui_BookWindow):
    # """A window to show the books available"""

    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)

        #Initialize db
        createdb.init_db()

        model = QSqlRelationalTableModel(self.bookTable)
        model.setEditStrategy(QSqlTableModel.OnManualSubmit)
        model.setTable("books")

        # Remember the indexes of the columns:
        author_idx = model.fieldIndex("author")
        genre_idx = model.fieldIndex("genre")

        # Set the relations to the other database tables:
        model.setRelation(author_idx, QSqlRelation("authors", "id", "name"))
        model.setRelation(genre_idx, QSqlRelation("genres", "id", "name"))

        # Set the localized header captions:
        model.setHeaderData(author_idx, Qt.Horizontal, self.tr("Author Name"))
        model.setHeaderData(genre_idx, Qt.Horizontal, self.tr("Genre"))
        model.setHeaderData(model.fieldIndex("title"), Qt.Horizontal, self.tr("Title"))
        model.setHeaderData(model.fieldIndex("year"), Qt.Horizontal, self.tr("Year"))
        model.setHeaderData(model.fieldIndex("rating"), Qt.Horizontal, self.tr("Rating"))

        if not model.select():
            print(model.lastError())

        # Set the model and hide the ID column:
        self.bookTable.setModel(model)
        self.bookTable.setItemDelegate(BookDelegate(self.bookTable))
        self.bookTable.setColumnHidden(model.fieldIndex("id"), True)
        self.bookTable.setSelectionMode(QAbstractItemView.SingleSelection)

        # Initialize the Author combo box:
        self.authorEdit.setModel(model.relationModel(author_idx))
        self.authorEdit.setModelColumn(model.relationModel(author_idx).fieldIndex("name"))

        self.genreEdit.setModel(model.relationModel(genre_idx))
        self.genreEdit.setModelColumn(model.relationModel(genre_idx).fieldIndex("name"))

        # Lock and prohibit resizing of the width of the rating column:
        self.bookTable.horizontalHeader().setSectionResizeMode(model.fieldIndex("rating"),
            QHeaderView.ResizeToContents)

        mapper = QDataWidgetMapper(self)
        mapper.setModel(model)
        mapper.setItemDelegate(BookDelegate(self))
        mapper.addMapping(self.titleEdit, model.fieldIndex("title"))
        mapper.addMapping(self.yearEdit, model.fieldIndex("year"))
        mapper.addMapping(self.authorEdit, author_idx)
        mapper.addMapping(self.genreEdit, genre_idx)
        mapper.addMapping(self.ratingEdit, model.fieldIndex("rating"))

        selection_model = self.bookTable.selectionModel()
        selection_model.currentRowChanged.connect(mapper.setCurrentModelIndex)

        self.bookTable.setCurrentIndex(model.index(0, 0))
        self.create_menubar()

Note

The Python version of the BookWindow class definition inherits from both QMainWindow and Ui_BookWindow, which is defined in the ui_bookwindow.py file that you generated earlier.

Here is how the rest of the code looks like:

C++ version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    ui.genreEdit->setModelColumn(
                model->relationModel(genreIdx)->fieldIndex("name"));

    // Lock and prohibit resizing of the width of the rating column:
    ui.bookTable->horizontalHeader()->setSectionResizeMode(
                model->fieldIndex("rating"),
                QHeaderView::ResizeToContents);

    QDataWidgetMapper *mapper = new QDataWidgetMapper(this);
    mapper->setModel(model);
    mapper->setItemDelegate(new BookDelegate(this));
    mapper->addMapping(ui.titleEdit, model->fieldIndex("title"));
    mapper->addMapping(ui.yearEdit, model->fieldIndex("year"));
    mapper->addMapping(ui.authorEdit, authorIdx);
    mapper->addMapping(ui.genreEdit, genreIdx);
    mapper->addMapping(ui.ratingEdit, model->fieldIndex("rating"));

    connect(ui.bookTable->selectionModel(),
            &QItemSelectionModel::currentRowChanged,
            mapper,
            &QDataWidgetMapper::setCurrentModelIndex
            );

    ui.bookTable->setCurrentIndex(model->index(0, 0));
    createMenuBar();
}

void BookWindow::showError(const QSqlError &err)
{
    QMessageBox::critical(this, "Unable to initialize Database",
                "Error initializing database: " + err.text());
}

void BookWindow::createMenuBar()
{
    QAction *quitAction = new QAction(tr("&Quit"), this);
    QAction *aboutAction = new QAction(tr("&About"), this);
    QAction *aboutQtAction = new QAction(tr("&About Qt"), this);

    QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(quitAction);

    QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
    helpMenu->addAction(aboutAction);
    helpMenu->addAction(aboutQtAction);

    connect(quitAction, &QAction::triggered, this, &BookWindow::close);
    connect(aboutAction, &QAction::triggered, this, &BookWindow::about);
    connect(aboutQtAction, &QAction::triggered, qApp, &QApplication::aboutQt);
}

void BookWindow::about()
{
    QMessageBox::about(this, tr("About Books"),
            tr("<p>The <b>Books</b> example shows how to use Qt SQL classes "
               "with a model/view framework."));
}

Python version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21

    def showError(err):
        QMessageBox.critical(self, "Unable to initialize Database",
                    "Error initializing database: " + err.text())

    def create_menubar(self):
        file_menu = self.menuBar().addMenu(self.tr("&File"))
        quit_action = file_menu.addAction(self.tr("&Quit"))
        quit_action.triggered.connect(qApp.quit)

        help_menu = self.menuBar().addMenu(self.tr("&Help"))
        about_action = help_menu.addAction(self.tr("&About"))
        about_action.setShortcut(QKeySequence.HelpContents)
        about_action.triggered.connect(self.about)
        aboutQt_action = help_menu.addAction("&About Qt")
        aboutQt_action.triggered.connect(qApp.aboutQt)

    def about(self):
        QMessageBox.about(self, self.tr("About Books"),
            self.tr("<p>The <b>Books</b> example shows how to use Qt SQL classes "
                "with a model/view framework."))

Now that all the necessary pieces are in place, try to put them together in main.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

import sys
from PySide2.QtWidgets import QApplication
from bookwindow import BookWindow
import rc_books

if __name__ == "__main__":
    app = QApplication([])

    window = BookWindow()
    window.resize(800, 600)
    window.show()

    sys.exit(app.exec_())

Try running this to see if you get the following output:

BookWindow with a QTableView and a few input fields

Now, if you look back at chapter2, you’ll notice that the bookdelegate.py loads the star.png from the filesytem. Instead, you could add it to a qrc file, and load from it. The later approach is rececommended if your application is targeted for different platforms, as most of the popular platforms employ stricter file access policy these days.

To add the star.png to a .qrc, create a file called books.qrc and the following XML content to it:

1
2
3
4
5
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
  <file>images/star.png</file>
</qresource>
</RCC>

This is a simple XML file defining a list all resources that your application needs. In this case, it is the star.png image only.

Now, run the pyside2-rcc tool on the books.qrc file to generate rc_books.py.

pyside2-rcc books.qrc > rc_books.py

Once you have the Python script generated, make the following changes to bookdelegate.py and main.py:

--- /tmp/snapshot-pyside-5.15-rel/pyside-setup/testenv-5.153_build/py3.6-qt5.15.0-64bit-release/pyside2/doc/rst/tutorials/portingguide/chapter2/bookdelegate.py
+++ /tmp/snapshot-pyside-5.15-rel/pyside-setup/testenv-5.153_build/py3.6-qt5.15.0-64bit-release/pyside2/doc/rst/tutorials/portingguide/chapter3/bookdelegate.py
@@ -48,10 +48,9 @@
 class BookDelegate(QSqlRelationalDelegate):
     """Books delegate to rate the books"""
 
-    def __init__(self, parent=None):
+    def __init__(self, star_png, parent=None):
         QSqlRelationalDelegate.__init__(self, parent)
-        star_png = os.path.dirname(__file__) + "\images\star.png"
-        self.star = QPixmap(star_png)
+        self.star = QPixmap(":/images/star.png")
 
     def paint(self, painter, option, index):
         """ Paint the items in the table.
--- /tmp/snapshot-pyside-5.15-rel/pyside-setup/testenv-5.153_build/py3.6-qt5.15.0-64bit-release/pyside2/doc/rst/tutorials/portingguide/chapter3/main-old.py
+++ /tmp/snapshot-pyside-5.15-rel/pyside-setup/testenv-5.153_build/py3.6-qt5.15.0-64bit-release/pyside2/doc/rst/tutorials/portingguide/chapter3/main.py
@@ -41,6 +41,7 @@
 import sys
 from PySide2.QtWidgets import QApplication
 from bookwindow import BookWindow
+import rc_books
 
 if __name__ == "__main__":
     app = QApplication([])

Although there will be no noticeable difference in the UI after these changes, using a .qrc is a better approach.

Now that you have successfully ported the SQL Books example, you know how easy it is. Try porting another C++ application.