[PyQt] Simple polling monitor application

Eric Frederich eric.frederich at gmail.com
Thu Jul 18 15:31:14 BST 2013


Hello,

I wrote an example monitoring application where I have a separate
thread monitoring something via an external process which could take
20ms to run or it could take 2 seconds to run.
Right now I have it just doing a time.sleep(1) for the example.

I want this monitoring to continuously happen.
It is an endless (while True) loop.
I'd prefer to use a QTimer but don't know how to get a QTimer to
trigger something in another thread.
The work needs to be done in another thread to keep the GUI responsive.

Can someone point me in the right direction or modify the following
code to use a QTimer rather than an infinite loop with a sleep
command?


#!/usr/bin/env python

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import time
from datetime import datetime

class MyThread(QThread):
    def __init__(self, parent=None):
        super(MyThread, self).__init__(parent)

    def run(self):
        count = 0
        while True:
            count += 1
            print 'do_something ', count, 'begin'
            time.sleep(1)
            self.emit(SIGNAL("new_info"), str(count) + ' ' +
str(datetime.now()))
            print 'do_something ', count, 'end'

class MyWidget(QWidget):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)
        self.setWindowTitle("Monitor")
        layout = QVBoxLayout()
        self.line = QLineEdit()
        layout.addWidget(self.line)
        self.setLayout(layout)

        self.mon = MyThread()
        self.connect(self.mon, SIGNAL("new_info"), self.on_new_info)
        self.mon.start()

    def on_new_info(self, info):
        print 'got new info', info
        self.line.setText(info)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    gm = MyWidget()
    gm.show()
    sys.exit(app.exec_())


More information about the PyQt mailing list