Python - QT

From Torben's Wiki

see [1]

Basic Application

import sys
from PyQt4 import QtGui
from PyQt4.QtCore import SIGNAL
from Ui_gui import Ui_MainWindow # load my QT Window ui, created by QT4-Designer + pyuic4

class MainWindowGUI(QtGui.QMainWindow, Ui_ofetGUI):
  def __init__(self, parent=None):
    QtGui.QMainWindow.__init__(self, parent)
    self.setupUi(self)

    # connect qt-signals to functions
    self.connect(self.ButtonStart,SIGNAL("clicked()"),self.clickedButtonStart) # ButtonStart is a name given by me

  def closeEvent(self, event): # define what to do when closing the window (e.g. via X-Button)
    ""

  def clickedButtonStart(self):
    ""

if __name__ == "__main__": # ============= Starting Point
  app = QtGui.QApplication(sys.argv)
  mainWindow = MainWindowGUI()
  mainWindow.show()
  sys.exit(app.exec_())

Widgets

QPushButton

=std. Buttons

setEnabled(True)
setEnabled(False)
Signal: "clicked()"

QCheckBox

setCheckState ( int )
int checkState () == 2 : # 0=unchecked, 1=partly, 2=checked

QSpinBox

enter int numbers

setValue( int )
int value()

QDoubleSpinBox

enter float numbers

setValue( float )
float value()
Signal: "valueChanged()"

QLineEdit

1-line textfield

QString text ()
setText ( String )

QLCDNumber

display(int)
display(float)

QProcessBar

int value () const
void setValue ( int value )

int minimum () const
void setMinimum ( int minimum )

int maximum () const
void setMaximum ( int maximum )

QLabel

setText( String )

QTableWidget

row = rowCount ()
insertRow(row)
while self.Table.rowCount () > 0:
  self.Table.removeRow(0)

tItem = QtGui.QTableWidgetItem()
tItem.setText( str( round(tA, 1) ))
#tItem.setBackground (QtGui.QColor("green"))
setItem(row,column,tItem)
# disable editing of table
self.Table.setEditTriggers(QAbstractItemView.NoEditTriggers)

QMessageBox

if ( os.path.isfile( file ) ):
  reply = QMessageBox.warning(self,  # choose: (warning, about, critical, question)
                              "Output file already exists!", # title
                              "Overwrite the file " + file + " ?", # message text
                              QMessageBox.Yes|QMessageBox.No # choose: (Yes, No, Cancel, Ok)
                              )
  if reply != QMessageBox.Yes : # if not "Yes" cancel here
    return

File Dialog

myFileDialog = QtGui.QFileDialog(self)
dirname = str ( myFileDialog.getExistingDirectory(self, 'Open dir', myVarStartDir) )

Signals

QObject.connect(self.ButtonStart, SIGNAL("clicked()"),self.myFunction)

# QThread notifies main gui:
self.emit(SIGNAL("MoinMoin"))
# gui:
QObject.connect(self.thread, SIGNAL("MoinMoin"), self.myFunction)

# QThread sends values to main gui
# in Thread
self.emit(SIGNAL("temperatureChanged(PyQt_PyObject)"),[self.t1, self.t2])
# main gui:
QObject.connect(self.thread, SIGNAL("temperatureChanged(PyQt_PyObject)"), self.temperatureChanged)
# ...
def temperatureChanged(self, temps):
  self.lcdTemp1.display(temps[0])
  self.lcdTemp2.display(temps[1])

Threads

Main File

# import my thread class MeasuringThread from file MeasuringThread
from MeasuringThread import MeasuringThread

self.thread = MeasuringThread(self) # give mainwindow as parameter to thread in order do be able to run its methods
self.connect(self.thread,SIGNAL("myUpdateSignal"),self.updateCalled)

def updateCalled(self)
  ""

Now the thread can be started and stopped via

self.thread.start() 
self.thread.stop()

Thread File

from PyQt4.QtCore import SIGNAL, QThread

class MeasuringThread(QThread):
  # A thread is started by calling QThread.start() never by calling run() directly!
  def __init__(self, mainwindowUebergabe, parent = None):
    QThread.__init__(self, parent)
    self.MainWindow = mainwindowUebergabe
    self.exiting = False # custum variable that is used to stop the thread

  def stop(self):
    self.exiting = True
    self.wait() # waits until run stops on his own

  def run(self):
    self.exiting = False
    while self.exiting == False :
      ""
      self.emit(SIGNAL("myUpdateSignal")) # send a signal to the main window
    # exit position of run function of thread. if exiting == true we end up here
    ""