There is an endless block when xml.etree.ElementTree.fromstring() function is called in the QThread. Also lots of other calls makes the QThread blocked like multiprocessing.Process().
Important to say that it is a pure block, no exception or break.
Here is the code (a little edited but same principle as the source):
from PyQt4.QtGui import *
from Ui_mainwindow import Ui_MainWindow
import sys
import xml.etree
class Bruton(QThread):
def __init__(self, mw):
super(Bruton, self).__init__(mw)
self.mw = mw
def run(self):
print("This message I see.")
tree = xml.etree.ElementTree.fromstring("<element>text</element>")
print("But this one never.")
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.init_bruton()
# When the form is shown...
def showEvent(self, arg1):
self.bruton.start()
def init_bruton(self):
self.bruton = Bruton(self)
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
The code as posted doesn't actually run, but with a couple minor changes it runs and works fine. Here is the code with modifications:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
import xml.etree.ElementTree
class Bruton(QThread):
def __init__(self, mw):
super(Bruton, self).__init__(mw)
self.mw = mw
def run(self):
print("This message I see.")
tree = xml.etree.ElementTree.fromstring("<element>text</element>")
print("But this one never.")
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.init_bruton()
# When the form is shown...
def showEvent(self, arg1):
self.bruton.start()
def init_bruton(self):
self.bruton = Bruton(self)
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
And here is the output:
$ python test.py
This message I see.
But this one never.
This is with Python 2.6.6, PyQt4 4.8.3, on Debian Unstable.
Can you try it in your environment and see if my modified example works for you? If so, you are on the road to a solution for your real code. =)
The code I've shown here is shortened (the source is divided to two files and __ini__.py). I noticed that the main module must be the module that starts the QApplication. So I added app.exec_() to the __init__.py which is the main module of my program.
Related
I have got this problem. I´m trying to set text on a lineEdit object on pyqt4, then wait for a few seconds and changing the text of the same lineEdit. For this I´m using the time.sleep() function given on the python Time module. But my problem is that instead of setting the text, then waiting and finally rewrite the text on the lineEdit, it just waits the time it´s supposed to sleep and only shows the final text. My code is as follows:
from PyQt4 import QtGui
from gui import *
class Ventana(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.button.clicked.connect(self.testSleep)
def testSleep(self):
import time
self.lineEdit.setText('Start')
time.sleep(2)
self.lineEdit.setText('Stop')
def mainLoop(self, app ):
sys.exit( app.exec_())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Ventana()
window.show()
sys.exit(app.exec_())
You can't use time.sleep here because that freezes the GUI thread, so the GUI will be completely frozen during this time.
You should probably use a QTimer and use it's timeout signal to schedule a signal for deferred delivery, or it's singleShot method.
For example (adapted your code to make it run without dependencies):
from PyQt4 import QtGui, QtCore
class Ventana(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setLayout(QtGui.QVBoxLayout())
self.lineEdit = QtGui.QLineEdit(self)
self.button = QtGui.QPushButton('clickme', self)
self.layout().addWidget(self.lineEdit)
self.layout().addWidget(self.button)
self.button.clicked.connect(self.testSleep)
def testSleep(self):
self.lineEdit.setText('Start')
QtCore.QTimer.singleShot(2000, lambda: self.lineEdit.setText('End'))
def mainLoop(self, app ):
sys.exit( app.exec_())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Ventana()
window.show()
sys.exit(app.exec_())
Also, take a look at the QThread sleep() function, it puts the current thread to sleep and allows other threads to run. https://doc.qt.io/qt-5/qthread.html#sleep
You can't use time.sleep here because that freezes the GUI thread, so the GUI will be completely frozen during this time.You can use QtTest module rather than time.sleep().
from PyQt4 import QtTest
QtTest.QTest.qWait(msecs)
So your code should look like:
from PyQt4 import QtGui,QtTest
from gui import *
class Ventana(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.button.clicked.connect(self.testSleep)
def testSleep(self):
import time
self.lineEdit.setText('Start')
QtTest.QTest.qWait(2000)
self.lineEdit.setText('Stop')
def mainLoop(self, app ):
sys.exit( app.exec_())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Ventana()
window.show()
sys.exit(app.exec_())
from PySide2 import QtGui,QtCore,QtWidgets
from PySide2.QtGui import*
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from shiboken2 import wrapInstance
import maya.OpenMayaUI as mui
import sys
class ui(QWidget):
def __init__(self,parent):
super(ui,self).__init__(parent)
self.resize(300,500)
self.mainWindow = QtWidgets.QMainWindow(parent)
self.setupUI(self.mainWindow)
self.setFocus()
def setupUI(self,mainWindow):
mymainWindow = QWidget(mainWindow)
mymainWindow.resize(300,500)
def mousePressEvent(self,e):
print 'sdfasdf'
if e.button()==Qt.RightButton:
print "Clickkkk"
def Show(self):
self.mainWindow.show()
class app():
def __init__(self):
self.ptr = mui.MQtUtil.mainWindow()
self.ptr = wrapInstance(long(self.ptr),QtWidgets.QWidget)
self.ui = ui(self.ptr)
def runApp(self):
self.ui.Show()
self.ui.setFocus()
tt = app()
tt.runApp()
Here is the code I'm testing on. After using wrapInstance the mouseEvent are no longer working.
But if I didn't wrap it it's work
not working
class app():
def __init__(self):
self.ptr = mui.MQtUtil.mainWindow()
self.ptr = wrapInstance(long(self.ptr),QtWidgets.QWidget)
self.ui = ui(self.ptr)
def runApp(self):
self.ui.Show()
self.ui.setFocus()
working
I Also change some parent structure in UI class
class app():
def __init__(self):
self.ui = ui()
def runApp(self):
self.ui.Show()
Can anyone explain why the MouseEvent won't work after I wrap it? And how to make it work?
The crux of the problem is this: self.ui.Show(). This runs your custom method, which in turn runs this self.mainWindow.show(). This causes self.mainWindow to show, but you subclassed mousePressEvent for ui, not self.mainWindow! So it's not running the event because you're clicking on the wrong widget.
Instead, since ui is a QWidget, call self.ui.show(). You may also have to put self.setWindowFlags(QtCore.Qt.Window) in ui's constructor. With this the mouse event runs as expected when the user clicks on it.
Some side notes:
I doubt that you actually want to create a QMainWindow in a QWidget. It just strikes as odd. Consider sub-classing a QMainWindow instead as it should be the 'top' widget.
Also try to avoid importing modules like from PySide2.QtCore import *, and import them like this instead from PySide2 import QtCore. It's bad practice, pollutes your module's scope, and makes the code much more unreadable/un-maintainable since it's hard to traceback where these variables come from.
Oh, and for the love of god, use some vertical white-spacing :)
I am trying to get my stdout displayed on a QTextEdit made via Qt Designer (PyQt5). Actually I made it work yet it doesn't show the info at the same time it was made. Instead it waits for the process to completely end and only then it shows all the information at once. I understand that this should be solved via threading. Also since the QTextEdit (itself) is a GUI element i need a different approach. I found the answer I was looking for here:
This question is referenced to:
Redirecting stdout and stderr to a PyQt4 QTextEdit from a secondary thread
#three_pineapples provided the answer.
My question is pretty much exactly the same, thus the answer is also correct. But my scenario is a little different and I'm having trouble making it work.
In all the threading answers I only see them using Classes. But the thing is in my main class I have a function that does all the stuff that would be printed on the QTextEdit. Sometimes it takes minutes to complete. I am looking for a way for the example code below to work using the answer provided by #three_pineapples.
Here is the example code:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtGui import QTextCursor
from ui_form import Ui_Form
class EmittingStream(QObject): # test
textWritten = pyqtSignal(str)
def write(self, text):
self.textWritten.emit(str(text))
class Form(QMainWindow):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
# Install the custom output stream
sys.stdout = EmittingStream(textWritten=self.normalOutputWritten) # test
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.pushButton_text.clicked.connect(self.test_write)
def __del__(self): # test
# Restore sys.stdout
sys.stdout = sys.__stdout__
def normalOutputWritten(self, text): # test
"""Append text to the QTextEdit."""
cursor = self.ui.textEdit.textCursor()
cursor.movePosition(QTextCursor.End)
cursor.insertText(text)
self.ui.textEdit.setTextCursor(cursor)
self.ui.textEdit.ensureCursorVisible()
def test_write(self): # this is a long, complicated function. its nested in this class. I don't have a way to get it out as a different class.
print("something written")
def main():
app = QApplication(sys.argv)
form = Form()
form.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Is there a way to get the provided solution to work -directly- on the (test_write) function in my main class? How would I implement it?
To make it more clear, from the reference link "LongRunningThing" class is not available for me. The function that needs to run on a separate thread is within the main class (named Form() in the example code). Perhaps a nested class could be used that encapsulates the test_write function inside my main class? Is that even possible?
For this case you can use the native threading of python:
import sys
import threading
import time
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtGui import QTextCursor
from ui_form import Ui_Form
class EmittingStream(QObject): # test
textWritten = pyqtSignal(str)
def write(self, text):
self.textWritten.emit(str(text))
class Form(QMainWindow):
finished = pyqtSignal()
def __init__(self, parent=None):
super(Form, self).__init__(parent)
# Install the custom output stream
sys.stdout = EmittingStream(textWritten=self.normalOutputWritten) # test
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.pushButton_text.clicked.connect(self.start_task)
self.finished.connect(lambda: self.ui.pushButton_text.setEnabled(True))
def start_task(self):
var = self.ui.lineEdit.text()
self.thread = threading.Thread(target=self.test_write, args=(args, ))
self.thread.start()
self.ui.pushButton_text.setEnabled(False)
def __del__(self): # test
# Restore sys.stdout
sys.stdout = sys.__stdout__
def normalOutputWritten(self, text): # test
"""Append text to the QTextEdit."""
cursor = self.ui.textEdit.textCursor()
cursor.movePosition(QTextCursor.End)
cursor.insertText(text)
self.ui.textEdit.setTextCursor(cursor)
self.ui.textEdit.ensureCursorVisible()
def test_write(self, *args):
var1 = args[0]
print("something written")
time.sleep(5) # simulate expensive task
print("something written ----")
self.finished.emit()
def main():
app = QApplication(sys.argv)
form = Form()
form.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I try to organize my code and therefore put some stuff into modules.
I would like several variables,, such as a statusBar(), in the main code section to be altered by imported modules.
I made a quick minimal working example to show what I mean:
Here is my main.py:
from PyQt4 import QtGui
import module
import sys
class ApplicationWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self.statusBar().showMessage("Main window initalized")
module.Test()
def main():
app = QtGui.QApplication(sys.argv)
form = ApplicationWindow()
form.show()
app.exec_()
if __name__ == "__main__":
main()
Here is module.py:
from PyQt4 import QtGui
class Test(QtGui.QMainWindow):
def __init__(self):
super(Test, self).__init__()
print 'hello'
self.statusBar().showMessage("Test module called", 6000)
The code prints "hello" and does not throw me any error, so I assume the module is successfully imported and Test is initialized, but it does not alter the statusBar() in my ApplicationWindow somehow. How can I achieve that? It's probably a silly mistake, so sorry in advance for bothering you!
the Test class have to reference to the ApplicationWindow class.
self.statusBar().showMessage("Test module called", 6000) will set a message on the status bar for the window of Test (A window that is lost to the void since it is never made visible or assigned to any variable)
Passing an instance of ApplicationWindow to Test would be one way to do what you want. Test also does not need to inherit from QtGui.QMainWindow for this.
from PyQt4 import QtGui
import module
import sys
class ApplicationWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self.statusBar().showMessage("Main window initalized", 6000)
module.Test(self)
def main():
app = QtGui.QApplication(sys.argv)
form = ApplicationWindow()
form.show()
app.exec_()
if __name__ == "__main__":
main()
# module.py
class Test(object):
def __init__(self, parent):
print 'hello'
parent.statusBar().showMessage("Test module called", 6000)
Hi I have designed a basic GUI in QT and created a .py file from it.
When the window starts up I want to add another menu item. I have tried a few pieces of code I found on google but nothing seems to work. The code will need to go in the method addAdminMenu()
from PyQt4 import QtGui
import sys
from supplypy.core.windows.main_window import Ui_MainWindow
class SRM(QtGui.QWidget):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
self.MainWindow = QtGui.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.MainWindow)
self.MainWindow.show()
sys.exit(self.app.exec_())
def addAdminMenu(self):
pass
#####Add code here to create a Admin menu####
if __name__ == '__main__':
srm = SRM()
It should be as simple as accessing the menuBar() of the QMainWindow and adding an item, for example: (I removed the Ui_MainWindow lines just because I don't know what it's for -- a Windows requirement?)
from PyQt4 import QtGui
import sys
class SRM(QtGui.QWidget):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
self.MainWindow = QtGui.QMainWindow()
self.menubar = self.MainWindow.menuBar()
self.MainWindow.show()
self.addAdminMenu()
sys.exit(self.app.exec_())
def addAdminMenu(self):
self.menubar.addMenu('&Admin');
if __name__ == '__main__':
srm = SRM()