Click here to Skip to main content
15,886,810 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I am new to programming and currently I am creating an application using python and PyQt with controller/joystick, using the pygame library. When I integrated the controller module, I created a while loop to handle all controller inputs, but the application crashed.

What I have tried:

So to prevent the application from crashing, I used the multithreading solution (Multithreading in PyQt With QThread) and created a thread where I moved my controller object to. My code is based on this tutorial https://realpython.com/python-pyqt-qthread/. The application isn't crashing anymore, but when the controller thread starts, the GUI becomes very slow and with a delay of time whenever I click on something.
Here's an extract from the code:

class Window(QMainWindow):
	def __init__(self):
		#create button for controller
        controllerOn = QPushButton("Controller On")
        controllerOn.clicked.connect(self.onControllerOn)
		
	def onControllerOn(self):
        if(self.controllerFirstConnexion == True):
			#create thread to handle controller inputs
            self.thread = QThread()
            self.worker = Worker()
            self.worker.moveToThread(self.thread)
            #do all the connections
            self.thread.started.connect(self.worker.run)
            self.worker.finished.connect(self.thread.quit)
            self.worker.finished.connect(self.worker.deleteLater)
            self.thread.finished.connect(self.thread.deleteLater)
			#start thread
            self.thread.start()
			
		while(self.worker.controllerConnected == True):
			QApplication.processEvents()
			self.reportProgressxyz(self.worker.x, self.worker.y, self.worker.z)
			
	def reportProgressxyz(self, xx, yy, zz):
		#do something 
		
	class Worker(QObject):
	    def run(self):
			pygame.init()
			joysticks = []

			#connect controller
			for i in range(0, pygame.joystick.get_count()):
				joysticks.append(pygame.joystick.Joystick(i))
				joysticks[-1].init()
				
			self.controllerConnected = True
			if pygame.joystick.get_count() == 1:
				while (self.controllerConnected == True) :
				#get input from controller


So now I have 2 while loops, one in the main thread and the other one in the controller thread. I thought the purpose of multithreading is to have multiple event loop functioning correctly at the same time, and yet my GUI is super slow when I use the controller.
Does anyone have a solution for this?

If I am not clear, please tell me so that I can explain more, this is my first time asking a question in here and I'm a beginner so bare with me.
Thank you so much.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900