Sending Data from Child to Parent Window in PyQt5 - python

What I can't do
I'm not able to send data back from a child to a parent window.
What I have
I've got a complex GUI with several windows sendíng data to child windows. Each window represents a unique Python-script in the same directory. There was no need to explicitely specify parents and childs, as the communication was always unidirectional (parent to child). However, now I need to send back data from childs to parents and can't figure out how to do this as each window (i.e. each class) has its own file.
Example
Here's a minimal example showing the base of what I want to accomplish.
What it does: win01 opens win02 and win02 triggers func in win01.
# testfile01.py
import sys
from PyQt5.QtWidgets import *
import testfile02 as t02
class win01(QWidget):
def __init__(self, parent=None):
super(win01, self).__init__(parent)
self.win02 = t02.win02()
self.button = QPushButton("open win02", self)
self.button.move(100, 100)
self.button.clicked.connect(self.show_t02)
def initUI(self):
self.center
def show_t02(self):
self.win02.show()
def func(self):
print("yes!")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = win01()
ex.show()
sys.exit(app.exec_())
##########################################################################
# testfile02.py
from PyQt5.QtWidgets import *
import testfile01 as t01
class win02(QWidget):
def __init__(self, parent=None):
super(win02, self).__init__(parent)
self.win01 = t01.win01()
self.button = QPushButton()
self.button.clicked.connect(self.win01.func)
def initUI(self):
self.center()
What I tried
Importing testfile01 in the second window always leads to the error:
RecursionError: maximum recursion depth exceeded.
Then, I tried the following approaches, but they didn't work either:
Not importing testfile01 in win02 and adjusting parent=None to different other objects
Importing testfile01 within the __init__ call of win02
Creating a signal in win02 to trigger func in win01
The Question
Is there a solution how to properly trigger func in win01 from win02?

Why are you getting RecursionError: maximum recursion depth exceeded?
You are getting it because you have a circular import that generates an infinite loop, in testfile01 you are importing the file testfile02, and in testfile02 you are importing testfile01, .... So that is a shows of a bad design.
Qt offers the mechanism of signals for objects to communicate information to other objects, and this has the advantage of non-dependence between classes that is a great long-term benefit (as for example that avoids circular import), so for that reason I think it is the most appropriate.
For this I will create the clicked signal in the class win02 that will be triggered by the clicked signal of the button, and make that clicked signal call the func:
testfile01.py
import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
import testfile02 as t02
class win01(QWidget):
def __init__(self, parent=None):
super(win01, self).__init__(parent)
self.win02 = t02.win02()
self.win02.clicked.connect(self.func)
self.button = QPushButton("open win02", self)
self.button.move(100, 100)
self.button.clicked.connect(self.show_t02)
def show_t02(self):
self.win02.show()
def func(self):
print("yes!")
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = win01()
ex.show()
sys.exit(app.exec_())
testfile02.py
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout
class win02(QWidget):
clicked = pyqtSignal()
def __init__(self, parent=None):
super(win02, self).__init__(parent)
self.button = QPushButton("call to func")
self.button.clicked.connect(self.clicked)
lay = QVBoxLayout(self)
lay.addWidget(self.button)
I recommend you read:
https://doc.qt.io/qt-5/signalsandslots.html

Both the Widgets are independent and have no link in between.
Set win01 parent of win02.
In class win01
Replace :
self.win01 = t02.win02()
#and
self.win02.show()
with:
self.win01 = t02.win02(self)
#and
self.win01.show()
and in class win02
Replace:
self.win02 = t01.win01()
#and
self.button.clicked.connect(self.win01.func)
with:
self.win02 = self.parent()
#and
self.button.clicked.connect(self.win02.func)

Related

PyQt5 Memory Management

I would like to understand how Python's and PyQt's garbage collectors work. In the following example, I create a QWidget (named TestWidget) that has a python attribute 'x'. I create TestWidget, interact with it, then close its window. Since I have set WA_DeleteOnClose, this should signal the Qt event loop to destroy my instance of TestWidget. Contrary to what I expect, at this point (and even after the event loop has finished) the python object referenced by TestWidget().x still exists.
I am creating an app with PyQt where the user opens and closes many many widgets. Each widget has attributes that take up a substantial amount of memory. Thus, I would like to garbage collect (in both Qt and Python) this widget and its attributes when the user closes it. I have tried overriding closeEvent and deleteEvent to no success.
Can someone please point me in the right direction? Thank you! Example code below:
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QTextEdit
from PyQt5.QtCore import Qt
class TestWidget(QWidget):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.setAttribute(Qt.WA_DeleteOnClose)
self.widget = None
self.x = '1' * int(1e9)
def load(self):
layout = QVBoxLayout(self)
self.widget = QTextEdit(parent=self)
layout.addWidget(self.widget)
self.setLayout(layout)
if __name__ == '__main__':
from PyQt5.QtWidgets import QApplication
import gc
app = QApplication([])
widgets = []
widgets.append(TestWidget(parent=None))
widgets[-1].load()
widgets[-1].show()
widgets[-1].activateWindow()
app.exec()
print(gc.get_referrers(gc.get_referrers(widgets[-1].x)[0]))
An important thing to remember is that PyQt is a binding, any python object that refers to an object created on Qt (the "C++ side") is just a wrapper.
The WA_DeleteOnClose only destroys the actual QWidget, not its python object (the TestWidget instance).
In your case, what's happening is that Qt releases the widget, but you still have a reference on the python side (the element in your list): when the last line is executed, the widgets list and its contents still exist in that scope.
In fact, you can try to add the following at the end:
print(widgets[-1].objectName())
And you'll get the following exception:
Exception "unhandled RuntimeError"
wrapped C/C++ object of type TestWidget has been deleted
When also the python object is deleted, then all its attributes are obviously deleted as well.
To clarify, see the following:
class Attribute(object):
def __del__(self):
print('Deleting Attribute...')
class TestWidget(QWidget):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.setAttribute(Qt.WA_DeleteOnClose)
self.widget = None
self.x = Attribute()
def load(self):
layout = QVBoxLayout(self)
self.widget = QTextEdit(parent=self)
layout.addWidget(self.widget)
self.setLayout(layout)
def __del__(self):
print('Deleting TestWidget...')
You'll see that __del__ doesn't get called in any case with your code.
Actual deletion will happen if you add del widgets[-1] instead.
Explanation
To understand the problem, you must know the following concepts:
Python objects are eliminated only when they no longer have references, for example in your example when adding the widget to the list then a reference is created, another example is that if you make an attribute of the class then a new reference is created.
PyQt (and also PySide) are wrappers of the Qt library (See 1 for more information), that is, when you access an object of the QFoo class from python, you do not access the C++ object but the handle of that object. For this reason, all the memory logic that Qt creates is handled by Qt but those that the developer creates has to be handled by himself.
Considering the above, what the WA_DeleteOnClose flag does is eliminate the memory of the C++ object but not the python object.
To understand how memory is being handled, you can use the memory-profiler tool with the following code:
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QTextEdit
from PyQt5.QtCore import Qt, QTimer
from PyQt5 import sip
class TestWidget(QWidget):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.setAttribute(Qt.WA_DeleteOnClose)
self.widget = None
self.x = ""
period = 1000
QTimer.singleShot(4 * period, self.add_memory)
QTimer.singleShot(8 * period, self.close)
QTimer.singleShot(12 * period, QApplication.quit)
def load(self):
layout = QVBoxLayout(self)
self.widget = QTextEdit()
layout.addWidget(self.widget)
def add_memory(self):
self.x = "1" * int(1e9)
if __name__ == "__main__":
from PyQt5.QtWidgets import QApplication
import gc
app = QApplication([])
app.setQuitOnLastWindowClosed(False)
widgets = []
widgets.append(TestWidget(parent=None))
widgets[-1].load()
widgets[-1].show()
widgets[-1].activateWindow()
app.exec()
In the previous code, in second 4 the memory of "x" is created, in second 8 the C++ object is eliminated but the memory associated with "x" is not eliminated and this is only eliminated when the program is closed since it is clear the list and hence the python object reference.
Solution
In this case a possible solution is to use the destroyed signal that is emitted when the C++ object is deleted to remove all references to the python object:
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QTextEdit
from PyQt5.QtCore import Qt, QTimer
from PyQt5 import sip
class TestWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.widget = None
self.x = ""
period = 1000
QTimer.singleShot(4 * period, self.add_memory)
QTimer.singleShot(8 * period, self.close)
QTimer.singleShot(12 * period, QApplication.quit)
def load(self):
layout = QVBoxLayout(self)
self.widget = QTextEdit()
layout.addWidget(self.widget)
def add_memory(self):
self.x = "1" * int(1e9)
class Manager:
def __init__(self):
self._widgets = []
#property
def widgets(self):
return self._widgets
def add_widget(self, widget):
self._widgets.append(widget)
widget.destroyed.connect(self.handle_destroyed)
def handle_destroyed(self):
self._widgets = [widget for widget in self.widgets if not sip.isdeleted(widget)]
if __name__ == "__main__":
from PyQt5.QtWidgets import QApplication
app = QApplication([])
app.setQuitOnLastWindowClosed(False)
manager = Manager()
manager.add_widget(TestWidget())
manager.widgets[-1].load()
manager.widgets[-1].show()
manager.widgets[-1].activateWindow()
app.exec()

The signal and slot within custom class including PyQt QWidget not working

I have some trouble customizing a class including a QPushButton and QLabel, and I just want to set the QPushButton checkable and define a slot to its toggled signal, in addition, the custom class inherents QObject.
The code is shown below,
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import pyqtSlot, QObject
class CustomButton(QPushButton):
def __init__(self, label='', parent=None):
super().__init__(label, parent)
self.setCheckable(True)
self.toggled.connect(self.update)
def update(self, state):
if state:
self.setStyleSheet('background-color: green')
else:
self.setStyleSheet('background-color: red')
class ButtonCtrl(QObject):
def __init__(self, parent=None, label=''):
super().__init__()
if isinstance(parent, QLayout):
col = QVBoxLayout()
parent.addLayout(col)
else:
col = QVBoxLayout(parent)
self.text = ['ON', 'OFF']
self.label = QLabel(label)
self.button = QPushButton('ON')
# self.button = CustomButton('ON')
col.addWidget(self.label)
col.addWidget(self.button)
self.button.setCheckable(True)
self.button.setChecked(True)
self.button.toggled.connect(self.update)
self.update(True)
self.label.setFont(QFont('Microsoft YaHei', 14))
self.button.setFont(QFont('Microsoft YaHei', 12, True))
self.button.toggle()
# #pyqtSlot(bool)
def update(self, state):
if state:
self.button.setText(self.text[0])
self.button.setStyleSheet('background-color: green')
else:
self.button.setText(self.text[-1])
self.button.setStyleSheet('background-color: red')
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# set the layout
layout = QVBoxLayout(self)
but = ButtonCtrl(layout, "Test")
#self.but = ButtonCtrl(layout, "Test")
btn = CustomButton()
layout.addWidget(btn)
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle('Fusion')
main = Window()
main.show()
sys.exit(app.exec_())
I have customized two buttons, named CustomButton(QPushButton) and ButtonCtrl(QObject), and I have tested the slot in the main window, however the background update slot works for CustomButton(QPushbutton) and does not work for ButtonCtrl(QObject), the slot function is not even invoked.
However, if I change the button member of ButtonCtrl(QObject) from QPushButton into my CustomButton(QPushButton), the it will work well in the main window. Furthermore, if the but in main window becomes a member of the main window class by setting self.but=ButtonCtrl(layout, "Test"), it will work as well.
I didn't find direct answer to it in Qt documentation which explains that
Signals are emitted by an object when its internal state has changed in some way that might be interesting to the object's client or owner. Signals are public access functions and can be emitted from anywhere, but we recommend to only emit them from the class that defines the signal and its subclasses.
I am not sure if the lifetime of the but causing this effect, hope to get an answer, thank you.
The problem is simple: The ButtonCtrl class object has a local scope so it will be destroyed, and why doesn't the same happen with the CustomButton class object? Well, because the ownership of a QWidget has its parent, and the parent of that button is the window, instead the ButtonCtrl object does not have it. In this case the solution is to extend the life cycle of the variable, and in the case of a QObject there are several options:
make the class member variable,
Place it in a container with a longer life cycle, or
establish a QObject parent with a longer life cycle.
Using the third alternative is just to change to:
class ButtonCtrl(QObject):
def __init__(self, parent=None, label=''):
super().__init__(parent)
# ...
The first option is the one commented on in your code:
self.but = ButtonCtrl(layout, "Test")
and the second is similar:
self.container = list()
but = ButtonCtrl(layout, "Test")
self.container.append(but)

Create another window of same class in PySide

I am creating a small GUI program using PySide. I am having difficulty creating another object of same class. What exactly I am trying to do is that when clicked on a button on MainWindow it should create another independent window of same class.
import sys
from PySide import QtCore, QtGui
class Sticky(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QMainWindow.__init__(self,parent)
self.initUI()
def initUI(self):
....
self.addToolBarElements()
....
self.show()
def addToolBarElements(self):
....
self.newwindow = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__),'icons/new.png')),"New Note",self)
self.newwindow.setStatusTip("New")
self.newwindow.triggered.connect(newwindow)
self.toolBar.addAction(self.newwindow)
def newwindow(self):
#how to create new object of same class
def run():
app = QtGui.QApplication(sys.argv)
notes = Sticky()
sys.exit(app.exec_())
Here is what I have tried:
I have tried multiprocessing but I didn't understand much. I tried calling run() method again but it gives error.
Do not call with the same name 2 different elements, in your case self.newwindow refers to the QAction as the method of the class, avoid it, that is a type of error easy to commit but difficult to find.
going to the point, you just have to create a new object of the class, but the problem is that the garbage collector will eliminate it, to avoid it there are 2 possible options, the first is to make the new window member of the class, or second store it in a list, that's the one I choose because I think you want to have several windows.
import sys
import os
from PySide import QtCore, QtGui
class Sticky(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QMainWindow.__init__(self,parent)
self.others_windows = []
self.initUI()
def initUI(self):
self.addToolBarElements()
self.show()
def addToolBarElements(self):
self.toolBar = self.addToolBar("toolBar")
self.newwindow = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__),'icons/new.png')), "New Note",self)
self.newwindow.setStatusTip("New")
self.newwindow.triggered.connect(self.on_newwindow)
self.toolBar.addAction(self.newwindow)
def on_newwindow(self):
w = Sticky()
w.show()
self.others_windows.append(w)
def run():
app = QtGui.QApplication(sys.argv)
notes = Sticky()
sys.exit(app.exec_())
run()

PyQt5 QFileDialog stops application from closing

I am trying to write a PyQt5 application that does the following:
Creates and opens a Main Window. The MainWindow has a function that opens a QFileDialog window.
Function to open QFileDialog can be triggered in two ways (1) from a file menu option called 'Open' (2) automatically, after the Main window is shown.
My problem is that I haven't found a way to get the QfileDialog to automatically open (2) that doesn't cause the application to hang when the main window is closed. Basic example of code can be found below:
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QMenuBar, QWidget,
QHBoxLayout, QCalendarWidget, QScrollArea, QFileDialog, QAction, QFrame)
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.openAction = QAction(QIcon('/usr/share/icons/breeze/places/64/folder-open.svg'), 'Open', self)
self.openAction.triggered.connect(self.openDialog)
self.menubar = QMenuBar(self)
fileMenu = self.menubar.addMenu('&File')
fileMenu.addAction(self.openAction)
self.event_widgets = EventWidgets(self)
self.setMenuBar(self.menubar)
self.setCentralWidget(self.event_widgets)
def openDialog(self):
ics_path = QFileDialog.getOpenFileName(self, 'Open file', '/home/michael/')
class EventWidgets(QWidget):
def __init__(self, parent):
super(EventWidgets, self).__init__(parent)
self.initUI()
def initUI(self):
self.calendar = QCalendarWidget(self)
self.frame = QFrame()
self.scrollArea = QScrollArea()
self.scrollArea.setWidget(self.frame)
horizontal_box = QHBoxLayout()
horizontal_box.addWidget(self.calendar)
horizontal_box.addWidget(self.scrollArea)
self.setLayout(horizontal_box)
if __name__ == '__main__':
app = QApplication(sys.argv)
app_window = MainWindow()
app_window.showMaximized()
app_window.openDialog()
sys.exit(app.exec_())
Code has been tested on KDE Neon and Arch Linux, both have same issue.
I can get round this issue by handling the close event of the Main Window manually - i.e. adding this function to MainWindow:
def closeEvent(self, event):
sys.exit()
But I am not sure a) why this is necessary b) if it is best practice.
I tried your code on macOS Sierra and it works as it's supposed to. However I would propose a different approach to solve your problem.
What you could do is to implement the showEvent() function in your MainWindow class, which is executed whenever a widget is displayed (either using .show() or .showMaximized()) and trigger your custom slot to open the QFileDialog. When doing this you could make use of a single shot timer to trigger the slot with some minimal delay: the reason behind this is that if you simply open the dialog from within the showEvent(), you will see the dialog window but not the MainWindow below it (because the QFileDialog is blocking the UI until the user perform some action). The single shot timer adds some delay to the opening of the QFileDialog, and allows the MainWindow to be rendered behind the modal dialog. Here is a possible solution (not that I made some minor changes to your code, which you should be able to easily pick up):
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.openAction = QtWidgets.QAction('Open', self)
self.openAction.triggered.connect(self.openDialog)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(self.openAction)
self.event_widgets = EventWidgets(self)
self.setCentralWidget(self.event_widgets)
def showEvent(self, showEvent):
QtCore.QTimer.singleShot(50, self.openDialog)
#QtCore.pyqtSlot()
def openDialog(self):
ics_path = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', '/Users/daniele/')
class EventWidgets(QtWidgets.QWidget):
def __init__(self, parent):
super(EventWidgets, self).__init__(parent)
self.calendar = QtWidgets.QCalendarWidget(self)
self.frame = QtWidgets.QFrame()
self.scrollArea = QtWidgets.QScrollArea()
self.scrollArea.setWidget(self.frame)
horizontal_box = QtWidgets.QHBoxLayout()
horizontal_box.addWidget(self.calendar)
horizontal_box.addWidget(self.scrollArea)
self.setLayout(horizontal_box)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app_window = MainWindow()
app_window.showMaximized()
sys.exit(app.exec_())

PyQt signal between QObjects

I'm trying to make a view and controller in PyQt where the view is emitting a custom signal when a button is clicked, and the controller has one of its methods connected to the emitted signal. It does not work, however. The respond method is not called when I click the button. Any idea what I did wrong ?
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import QPushButton, QVBoxLayout, QDialog, QApplication
class TestView(QDialog):
def __init__(self, parent=None):
super(TestView, self).__init__(parent)
self.button = QPushButton('Click')
layout = QVBoxLayout()
layout.addWidget(self.button)
self.setLayout(layout)
self.connect(self.button, SIGNAL('clicked()'), self.buttonClicked)
def buttonClicked(self):
self.emit(SIGNAL('request'))
class TestController(QObject):
def __init__(self, view):
self.view = view
self.connect(self.view, SIGNAL('request'), self.respond)
def respond(self):
print 'respond'
app = QApplication(sys.argv)
dialog = TestView()
controller = TestController(dialog)
dialog.show()
app.exec_()
Works for me - might be the version of Qt/PyQt you're using, but there are a couple things you can try:
Use a proper method syntax - so SIGNAL('request()') vs. SIGNAL('request')
Use new-style signal syntax
The style you are using is the old-style PyQt syntax and the new-style signal/slot definition is recommended:
import sys
from PyQt4.QtCore import QObject, pyqtSignal # really shouldn't import * here...QtCore library is quite large
from PyQt4.QtGui import QPushButton, QVBoxLayout, QDialog, QApplication
class TestView(QDialog):
request = pyqtSignal()
def __init__(self, parent=None):
super(TestView, self).__init__(parent)
self.button = QPushButton('Click')
layout = QVBoxLayout()
layout.addWidget(self.button)
self.setLayout(layout)
self.button.clicked.connect(self.buttonClicked)
def buttonClicked(self):
self.request.emit()
class TestController(QObject):
def __init__(self, view):
super(QObject, self).__init__()
self.view = view
self.view.request.connect(self.respond)
def respond(self):
print 'respond'
app = QApplication(sys.argv)
dialog = TestView()
controller = TestController(dialog)
dialog.show()
app.exec_()
Again tho, I would really, really discourage building your code this way...you are creating a lot of unnecessary work and duplication of objects when you don't need to.

Categories

Resources