PyQt — Part 2
3 08 2009I’ve been a little busy the last few weeks and haven’t really had much time to write a good post. I promise more next week. This week I’m using an example that I used in my lightning talk at PyOhio. It’s pretty simple and straight forward, it just gives you more of an idea of how to use PyQt in an organized manor.
PyQt-Part2.py (Download):
#!/usr/bin/python import sys from PyQt4 import QtGui, QtCore class LanguageSelectorWidget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('LanguageSelector') comboBox = QtGui.QComboBox(self) comboBox.addItem('Python') comboBox.addItem('Java') comboBox.addItem('Ruby') self.textEdit = QtGui.QTextEdit(self) okButton = QtGui.QPushButton('Ok', self) cancelButton = QtGui.QPushButton('Cancel', self) buttonLayout = QtGui.QHBoxLayout() buttonLayout.addWidget(okButton) buttonLayout.addWidget(cancelButton) mainlayout = QtGui.QVBoxLayout(self) mainlayout.addWidget(comboBox) mainlayout.addWidget(self.textEdit) mainlayout.addLayout(buttonLayout) self.connect(comboBox, QtCore.SIGNAL('currentIndexChanged(int)'), self.comboxBoxUpdated) self.connect(okButton, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) self.connect(cancelButton, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) comboBox.setCurrentIndex(1) def __del__(self): print self.textEdit.toPlainText() def comboxBoxUpdated(self, index): if index == 0: self.textEdit.setText('Snakes are scary!') elif index == 1: self.textEdit.setText('Coffee is hot!') else: self.textEdit.setText('Diamonds are forever!') # Run application if __name__ == "__main__": app = QtGui.QApplication(sys.argv) qb = LanguageSelectorWidget() qb.show() sys.exit(app.exec_())
Here is a preview of what the above code will generate (XFCE4 in Linux):

In the above example my class “LanguageSelectorWidget” inherits from “QWidget” (a base widget class). Doing this allows me to easily contain all of the other widgets inside my class and easily manage their communication. This example would make a great dialog for a larger application. You can see in the destructor the final value in the text box is printed to the command-line. This could also be returned to the invoking object, written to a database, used to invoke another program, etc.
Categories : General, Python, Qt Framework

