Thursday, September 12, 2013

PyQt, building my first GUI

The lab I'm in wrote and maintains a software package for analyzing microscope images generated with a laser microscope. The software is all command line and would really benefit from guis in a couple key spots. Towards this end, I'm writing my first gui! I decided to work in PyQt, and there's a lot to learn! Most of all, I need to get familiar with the modules available and their options (best reference I've found so far: http://pyqt.sourceforge.net/Docs/PyQt4/classes.html):

So far, I've played with:

QtGui.QLabel
QtGui.QSlider
QtGui.QLCDNumber
QtGui.QFrame

Here is how I'm using them:

I'm using QLabel just to display some text in my window:
# number of pixels are measured from top left corner
red = QtGui.QLabel(self)
red.setGeometry(10,10,100,30) # pixels over, pixels down, pixels wide, pixels tall
red.setText('Red')

Note, it seems oddly hard to change the color of the text, fontsize, etc. It is strange that it is not a clear option, but at least, I can get plain, black text displayed!

I'm using sliders as a way for the user to change the input, QtGui.QSlider:
sld = QtGui.QSlider(QtCore.Qt.Horizontal, self) # slider horizontal rather than default vertical
sld.setGeometry(60,40,100,30) # pixels over, pixels down, pixels wide, pixels tall
sld.setMinimum(0) # redefine what numbers the endpoints of the slider stand for
sld.setMaximum(255)
#EVENT HANDLERS
sld.valueChanged.connect(lcd.display) #connects the value of the sld to the lcd display

The lcd-style number display had to be defined before the slider was connectd to it:
lcd = QtGui.QLCDNumber(self)
lcd.setGeometry(60, 80,100,30)

I used QtGui.QFrame to display a solid purple square in the window:
square = QtGui.QFrame(self)
square.setGeometry(100, 100, 30, 30)   
square.setStyleSheet("QWidget { background-color: %s }" %  
         QtGui.QColor(100, 0, 100).name() ) 

Note, using the style sheet, I was able to change the color via the QColor module!