Reputation: 466
Basically I have a program that will create a basic hello world program in PySide qt framework. The difference is that it does print("loop")
in a while loop before exec_()
is called. The problem with that the loop won't finish until the user is done with the program, so it will only call exec_()
when the loop's done.
My problem is that if you run it like this, print("loop")
will run, but the window won't respond, and doesn't display "Hello, loop!"). If you indent qt_app.exec_()
under while running:
, then the window will respond, but print("loop")
only executes once before closing the window, and executes only once after closing it.
I need to be able to have the main window be responding while its printing "loop" to the console multiple times.
import sys
from PySide.QtCore import *
from PySide.QtGui import *
qt_app = QApplication(sys.argv)
label = QLabel('Hello, loop!')
label.show()
running = True #only set to False when user is done with app in the real code.
while running:
#I am handling connections here that MUST be in continual while loop
print("loop")
qt_app.exec_()
Upvotes: 4
Views: 2741
Reputation: 46586
If you want to have a GUI application you have to let the GUI event loop take over the main thread.
The solution for your problem would be to create a separate thread that will do the printing while you let the qt event loop take over the main thread.
Your thread will be running in the background, doing it's stuff and (since I set it to be daemon) it will stop when the application finishes, or the running
variable is set to False
.
import sys
import time
import threading
from PySide.QtCore import *
from PySide.QtGui import *
qt_app = QApplication(sys.argv)
label = QLabel('Hello, loop!')
label.show()
running = True #only set to False when user is done with app in the real code.
def worker():
global running
while running:
#I am handling connections here that MUST be in continual while loop
print("loop")
time.sleep(0.5)
thread = threading.Thread(target=worker)
thread.setDaemon(True)
thread.start()
qt_app.exec_()
But this is a bad example since you shouldn't use global mutable variables in thread without locking, etc. etc. etc... But that's all in the docs.
Upvotes: 2