Chapter 4 - Add a QTableView

Now that you have a QMainWindow, you can include a centralWidget to your interface. Usually, a QWidget is used to display data in most data-driven applications. Use a table view to display your data.

The first step is to add a horizontal layout with just a QTableView. You can create a QTableView object and place it inside a QHBoxLayout. Once the QWidget is properly built, pass the object to the QMainWindow as its central widget.

Remember that a QTableView needs a model to display information. In this case, you can use a QAbstractTableModel instance.

Note

You could also use the default item model that comes with a QTableWidget instead. QTableWidget is a convenience class that reduces your codebase considerably as you don’t need to implement a data model. However, it’s less flexible than a QTableView, as QTableWidget cannot be used with just any data. For more insight about Qt’s model-view framework, refer to the Model View Programming <http://doc.qt.io/qt-5/model-view-programming.html> documentation.

Implementing the model for your QTableView, allows you to: - set the headers, - manipulate the formats of the cell values (remember we have UTC time and float numbers), - set style properties like text alignment, - and even set color properties for the cell or its content.

To subclass the QAbstractTable, you must reimplement its virtual methods, rowCount(), columnCount(), and data(). This way, you can ensure that the data is handled properly. In addition, reimplement the headerData() method to provide the header information to the view.

Here is a script that implements the CustomTableModel:

 1
 2from PySide2.QtCore import Qt, QAbstractTableModel, QModelIndex
 3from PySide2.QtGui import QColor
 4
 5
 6class CustomTableModel(QAbstractTableModel):
 7    def __init__(self, data=None):
 8        QAbstractTableModel.__init__(self)
 9        self.load_data(data)
10
11    def load_data(self, data):
12        self.input_dates = data[0].values
13        self.input_magnitudes = data[1].values
14
15        self.column_count = 2
16        self.row_count = len(self.input_magnitudes)
17
18    def rowCount(self, parent=QModelIndex()):
19        return self.row_count
20
21    def columnCount(self, parent=QModelIndex()):
22        return self.column_count
23
24    def headerData(self, section, orientation, role):
25        if role != Qt.DisplayRole:
26            return None
27        if orientation == Qt.Horizontal:
28            return ("Date", "Magnitude")[section]
29        else:
30            return "{}".format(section)
31
32    def data(self, index, role=Qt.DisplayRole):
33        column = index.column()
34        row = index.row()
35
36        if role == Qt.DisplayRole:
37            if column == 0:
38                raw_date = self.input_dates[row]
39                date = "{}".format(raw_date.toPython())
40                return date[:-3]
41            elif column == 1:
42                return "{:.2f}".format(self.input_magnitudes[row])
43        elif role == Qt.BackgroundRole:
44            return QColor(Qt.white)
45        elif role == Qt.TextAlignmentRole:
46            return Qt.AlignRight
47
48        return None
49

Now, create a QWidget that has a QTableView, and connect it to your CustomTableModel.

 1
 2from PySide2.QtWidgets import (QHBoxLayout, QHeaderView, QSizePolicy,
 3                               QTableView, QWidget)
 4
 5from table_model import CustomTableModel
 6
 7
 8class Widget(QWidget):
 9    def __init__(self, data):
10        QWidget.__init__(self)
11
12        # Getting the Model
13        self.model = CustomTableModel(data)
14
15        # Creating a QTableView
16        self.table_view = QTableView()
17        self.table_view.setModel(self.model)
18
19        # QTableView Headers
20        self.horizontal_header = self.table_view.horizontalHeader()
21        self.vertical_header = self.table_view.verticalHeader()
22        self.horizontal_header.setSectionResizeMode(
23                               QHeaderView.ResizeToContents
24                               )
25        self.vertical_header.setSectionResizeMode(
26                             QHeaderView.ResizeToContents
27                             )
28        self.horizontal_header.setStretchLastSection(True)
29
30        # QWidget Layout
31        self.main_layout = QHBoxLayout()
32        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
33
34        ## Left layout
35        size.setHorizontalStretch(1)
36        self.table_view.setSizePolicy(size)
37        self.main_layout.addWidget(self.table_view)
38
39        # Set the layout to the QWidget
40        self.setLayout(self.main_layout)
41

You also need minor changes to the main_window.py and main.py from chapter 3 to include the Widget inside the MainWindow.

In the following snippets you’ll see those changes highlighted:

 1
 2from PySide2.QtCore import Slot
 3from PySide2.QtGui import QKeySequence
 4from PySide2.QtWidgets import QMainWindow, QAction
 5
 6
 7class MainWindow(QMainWindow):
 8    def __init__(self, widget):
 9        QMainWindow.__init__(self)
10        self.setWindowTitle("Eartquakes information")
11        self.setCentralWidget(widget)
12        # Menu
13        self.menu = self.menuBar()
14        self.file_menu = self.menu.addMenu("File")
15
16        ## Exit QAction
17        exit_action = QAction("Exit", self)
18        exit_action.setShortcut(QKeySequence.Quit)
19        exit_action.triggered.connect(self.close)
20
21        self.file_menu.addAction(exit_action)
22
23        # Status Bar
24        self.status = self.statusBar()
25        self.status.showMessage("Data loaded and plotted")
26
27        # Window dimensions
28        geometry = qApp.desktop().availableGeometry(self)
29        self.setFixedSize(geometry.width() * 0.8, geometry.height() * 0.7)
30
 1
 2import sys
 3import argparse
 4import pandas as pd
 5
 6from PySide2.QtCore import QDateTime, QTimeZone
 7from PySide2.QtWidgets import QApplication
 8from main_window import MainWindow
 9from main_widget import Widget
10
11
12def transform_date(utc, timezone=None):
13    utc_fmt = "yyyy-MM-ddTHH:mm:ss.zzzZ"
14    new_date = QDateTime().fromString(utc, utc_fmt)
15    if timezone:
16        new_date.setTimeZone(timezone)
17    return new_date
18
19
20def read_data(fname):
21    # Read the CSV content
22    df = pd.read_csv(fname)
23
24    # Remove wrong magnitudes
25    df = df.drop(df[df.mag < 0].index)
26    magnitudes = df["mag"]
27
28    # My local timezone
29    timezone = QTimeZone(b"Europe/Berlin")
30
31    # Get timestamp transformed to our timezone
32    times = df["time"].apply(lambda x: transform_date(x, timezone))
33
34    return times, magnitudes
35
36
37if __name__ == "__main__":
38    options = argparse.ArgumentParser()
39    options.add_argument("-f", "--file", type=str, required=True)
40    args = options.parse_args()
41    data = read_data(args.file)
42
43    # Qt Application
44    app = QApplication(sys.argv)
45
46    widget = Widget(data)
47    window = MainWindow(widget)
48    window.show()
49
50    sys.exit(app.exec_())
51