SQL GUI example – QTableView

In this section we’ll discuss the development of a small python app that will connect to a MySQL database and will allow the user to manipulate the database using a Qt graphical user interface. The interface consists in a QTableView which will display a table from the database, 2 QLabels & QLineEdits where the user can input data to insert or update the database, and 6 QPushButtons.

This time I’m going to start with the full code for the app. Here’s the pastebin link:


We start by creating our MainForm class and building the constructor, where we define the user interface, connect to the database and connect the signals to the event handler methods.

We also define the QTableView and it’s model, QSqlQueryModel:

self.db_table = QtGui.QTableView(self)
self.model = QtSql.QSqlQueryModel()
 self.model.setQuery("SELECT * FROM simpsons")
 self.model.setHeaderData(1, QtCore.Qt.Horizontal, self.tr("First Name"))
 self.model.setHeaderData(2, QtCore.Qt.Horizontal, self.tr("Last Name"))
 self.db_table.hideColumn(0) #hide column 'id'

The model will hold the data we read from the database and will display it on the table. We get the data using:

self.model.setQuery("SELECT * FROM simpsons")

The ‘get_current_id()‘ method returns the id from the database of the current selected row from the QTableView.

<pre>if self.db_table.currentIndex():
   index = self.db_table.currentIndex().row()
   db_id = self.model.record(index).value("simpsons_id")
   return db_id</pre>

If a row is selected in the QTableView it gets it’s index and uses that index to get the row’s database table id.

The rest of the methods were discuses in the previous tutorial: QtSql

This entry was posted in database, PySide, Python and tagged , , , , , , , , , , , . Bookmark the permalink.

2 Responses to SQL GUI example – QTableView

  1. tipu says:

    i’ve been looking for a solid example that shows the use of qtableview and a database connection, most are incomplete. thanks !

  2. javid says:

    Thank you so much …. this was very useful for me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s