Marvelous MVC with QSRTM

UPDATE 2014-06-01: Added links to code examples that helped me learn how to do this.

Here it is, people…brought to you by the magic of the QSqlRelationalTableModel: my editable transactions display widget, complete with combo boxes for selecting categories and accounts from the ‘accounts’ table, coded in elegant, model-view-controller style and in less than 70 lines of code, counting the blank lines added for readability. I’m viewing data from multiple Sqlite tables, even editing, without a single line of SQL. All I have to do is tell ‘QSRTM’ (my affectionate nickname for my new friend, QSqlRelationalTableModel) the name of the table and what to display, and he obediently gets what I want the way I want it. Meanwhile Tkinter is throwing a tempter tantrum in the corner when I try to ask it nicely to please synchronize row selection across a set of list boxes.

While documentation such as Pyside’s is excellent and thorough, I find I need examples of how to use a class. I experiment with altering example code to fit what I am trying to accomplish, and when I feel like I have a grasp of the class’s basics, I go back to the documentation to get a full appreciation of all its capabilities. Two table model examples in particular were essential to me figuring out how to use the ‘QSRTM’: this one which demonstrates general use of a table model, and this one which is a ‘QSRTM’ example.

Screenshot below, and my code is here.



Unbounded by a binding

Once upon a time, fresh out of Code Academy, I Googled for a way to design a GUI in Python. I came across Qt Designer. Cool! It reminded me of Microsoft Access and Visual Basic. I could lay out windows, buttons, boxes and so on just the way I wanted, set their properties and add some code. I began learning about “slots” and “signals”, Qt’s system of connecting what a widget is supposed to do to what the user does to it. But before long, it hit me:

The code I was using to create this wonderful GUI was not Python; it was Qt.

Somewhere along the line I’d read that Qt could be used to make a GUI for use in Python, yet Qt and Python are completely separate languages, so how, I asked myself, could I possibly use a GUI created in Qt, in Python? It sounded about as likely as running a Mac OS application on my Android phone. For whatever reason at that time, I couldn’t find a clear answer to this, and other options such as wxPython and Tkinter drifted into my view, so Qt was quickly forgotten. wxPython looked cool but when I decided it would be best for me as a newbie to learn in Python 3, wxPython quickly dropped off my radar. I noted Tkinter is included with Python and has been around forever, so it seemed to be the best option of the three. Unfortunately, I found Tkinter’s documentation to be fragmented and in some cases, ancient. Trying to produce a simple table object gradually wore me down over a period of months, which taught me the hard way that Tkinter is apparently just fine for GUIs with simple buttons, text boxes and lists, but nearly useless for data objects any more complex than a listbox. The one or two times I’ve run across table-like objects for Tkinter, I found they were not compatible with Python 3.

Luckily, I was only one more frustrated Google search away from discovering an amazing concept that brings diverse languages together in harmony, letting them play ball joyously with one another and get along like BFFs:


I eventually discovered Pyside, which re-introduced me to its friend Qt, and now Qt and I are buddies again! The secret? Lay out, code and design the GUI of my dreams in Qt, and when done, it’s only one magical command-line incantation away form being transformed into a Python class object, ready to be called upon any time! Pyside changed the direction of my DataQ project and injected it, and my Python learning adventure, with new life. Before long I was able to finally create a real GUI widget for my app and even able to my data into it.

Next step: wrapping my brain around model-view programming.


My original mockup idea..


So close!

QTableView knocks Tkinter off the ‘table’



Have I got a deal for you! How about a GUI widget with over double the functionality, with less than half the code? Here it is:

import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtSql import *

# My function for assembling SQL queries for my 'transactions' table. I'll share the code another time.
from dq_sql import *

app = QApplication(sys.argv)

class DqTableForm(QWidget):
    def __init__(self, parent = None):


        db = QSqlDatabase.addDatabase("QSQLITE")

        self.DqModel = QSqlQueryModel()

# My TransQry function takes parameters and returns a SQL query using the parameters as criteria for filtering my 'transactions' table.      

self.DqModel.setQuery(TransQry("2014-03-01","2014-03-31","DESC","","","202",""), db)

        self.DqTable = QTableView()

        grid = QGridLayout()

form = DqTableForm()

See? Less than 45 lines. Sure beats the nearly 100-line, marginally useful alternative, which I have been sweating and struggling under for months. Lesson learned: there’s a very fuzzy boundary between challenging myself toward productive learning, and finding the most efficient solution to a need. In this instance, given the complex data filtering and sorting I’m trying to accomplish, Qt’s QTableView soundly beats anything Tkinter is even remotely capable of without astronomically more code. Shout out to Bo’s Qt GUI tutorials for introducing me to Qt, the documentation for the PySide Python Qt bindings for helping me figure out QTableView, and to my friend and constant companion Google, for helping me evolve.

Revolution! (tossing out Tkinter)


Wow, a real, live Python visual app designer!

In the last few weeks I realized I have a long way to go to figure out how the MultiListbox code works…it seems like even the simple function of selecting a line of data requires torturous hand-coding. Almost two months after setting out on my quest for a Python data management application, I am still tripping and stumbling over a single GUI element. And yet all it does is display columns of data, something Microsoft Access does in its sleep, and the MultiListbox isn’t even editable. I’ve become distracted and discouraged. There are functions in the MLB class that I’m not even close to understanding, and there is no detailed explanation of the code anywhere. Lately I’ve thinking, there’s got to be a better way. There’s got to be a way where I can focus my coding on what I want the GUI widgets to DO, instead of struggling just to bring them into functional existence.

So, this afternoon, I once again Googled “Python GUI builder” or something like this and found this series of videos on building Python GUI applications with the Qt framework.

The first series of videos walk the user through how to download and install a Python interface to the Qt development framework, in this case PySide. The author of this video series uses PyCharm on Windows 7, so his desktop and mine are nearly identical, meaning it couldn’t be easier to follow along with him.  The first few videos walk through the creation of simple Qt-based GUI applications such as a calculator. Eventually it moves on to QtDesigner, which, wonder of wonders, is a “drag and drop” GUI designer very much like Microsoft Access and Visual Basic. Where Tkinter requires 100% hand-coding of just about every step of a widget’s function, even PySide coding by itself without the graphical Qt Designer seems much simpler and less labor intensive.

Yes, I have spent many months on Tkinter. Yes, it seemed like I was on the right track when I discovered the MultiListbox. I enjoyed, for a time, the challenge of trying to figure it out. But somewhere along the line, it wasn’t fun anymore. It was a chore. This made it all too easy to become distracted with other projects. That was the signal that something was wrong. I like a challenge and I have loved learning Python, but when it’s no longer enjoyable, it’s no longer worth doing.  It’s a little intimidating to think of learning a completely new GUI builder.  However once I saw that drag and drop designer, that shimmering promise of instantly knowing my app will look the way I want it to without all the trial and error, and each item I drop into my app already knowing how to do what it’s supposed to and all I have to to is give it parameters,  I thought, “This could make Python fun again.” So off I go on my next, unexpected Python path. I’m going spend the next phase of my Python adventure getting as much as I can out of Mr. Milanovic’s videos, and of course, sharing the results.

A slow but sure learning process

It would be easy to grab a chunk of someone else’s code, modify it only as necessary, and through a lot of trial and error get it to do what I want.  That is what I originally set out to do when I discovered the MultiListbox custom widget in this project. Using this method I might be able to patch together something functional, without ever learning in depth about how the code actually works. This course of action is a continual temptation to my impatient self, especially now as I am grappling with the most complex GUI object in my DataQ application.

But that is not my goal. I don’t just want to learn how to use Python for specific tasks; I want to learn how Python WORKS. The MultiListbox fascinated me because it’s not just any old Tkinter widget; it’s a custom widget made out of other widgets — in this case, a series of Listboxes put together to display rows of data. In examining the MultiLisbox code, I realized I knew very little how even a single Listbox works, let alone a group of them squashed together and synchronized. I therefore decided to learn about and experiment with Listboxes, learning how they work from the ground up. I have found it hard to stay focused. Sometimes I get away from Python completely for days at time because my brain just feels fried by it.

Despite the challenges, I’m happy to report that I’m making progress. I’ve even started designing my very own MultiListbox class (mostly) without even looking at the original code! My version makes each individual column in the MultiListbox its own class, and I use the .grid() geometry manager instead of the often unpredictable .pack(). Here is the ‘rough draft’: Rob’s MultiListbox.