Click a button and change MainWindow - python

I am learning Qt and I am interesting in how to change some features of MainWindow.
I was trying this code, but there were some errors when I clicked the first button:
Traceback (most recent call last):
File "\main.py", line 15, in run_the_first_button_was_clicked
the_first_button_was_clicked(self)
File "clickedButton.py", line 15, in the_first_button_was_clicked
self.button2.clicked.connect(self.the_second_button_was_clicked)
AttributeError: 'MainWindow' object has no attribute 'the_second_button_was_clicked'
what I did wrong (how could I do 'the_second_button_was_clicked' callable )?
main.py
from PySide2.QtWidgets import QApplication, QMainWindow, QPushButton
import sys
from clickedButton import the_first_button_was_clicked, the_second_button_was_clicked
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("MainWindow")
self.button1 = QPushButton("button1")
self.button1.clicked.connect(self.run_the_first_button_was_clicked)
self.setCentralWidget(self.button1)
def run_the_first_button_was_clicked(self):
the_first_button_was_clicked(self)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
clickedButton.py
from PySide2.QtWidgets import QPushButton
from PySide2 import QtCore
def the_first_button_was_clicked(self):
self.setWindowTitle("the_first_button_was_clicked next will be the_second_button_was_clicked")
self.resize(800, 600)
self.button1.setText("the_first_button_was_clicked")
self.button1.setEnabled(False)
self.button2 = QPushButton("button2")
self.button2.setGeometry(QtCore.QRect(100, 100, 150, 150))
self.button2.setVisible(True)
self.button2.clicked.connect(self.the_second_button_was_clicked)
def the_second_button_was_clicked(self):
self.setWindowTitle("the_second_button_was_clicked")
self.resize(600, 800)

The issue has nothing to do with PyQt, but with how classes and instances work.
The first argument of instance methods always refers to the instance of the class, and it's called self just for convention: it could actually be named in any way as long as its syntax is valid, just like any other variable.
When using functions that are declared outside a class, it's good practice to avoid that naming convention (mostly to avoid confusion when reading code).
What is happening is that the self in def the_first_button_was_clicked(self): refers to the instance of MainWindow, which has no the_second_button_was_clicked method, hence the AttributeError exception.
The point is that both your functions are just functions, not methods (which are functions of an instance or a class): they are not members of the class.
Also note that creating a direct connection to the function will not work, as the self argument is only "created" when a function is a method.
As Heike pointed out in the comments, a possibility is to use lambda, which allows keeping an actual reference to the instance, while directly calling the function, which will be executed using the self argument provided, exactly as you did in run_the_first_button_was_clicked.
In the following examples I'm replacing self with mainWinInstance in order to make things more clear (which is the reason for which self should not be used in these cases).
def the_first_button_was_clicked(mainWinInstance):
# we reference the function locally to this script, adding the "self" argument
mainWinInstance.button2.clicked.connect(lambda:
the_second_button_was_clicked(mainWinInstance))
def the_second_button_was_clicked(mainWinInstance):
# "self" (mainWinInstance) was manually added to the function arguments
mainWinInstance.setWindowTitle("the_second_button_was_clicked")
mainWinInstance.resize(600, 800)
Another possibility is to make the second function a member of the instance:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# ...
self.the_second_button_was_clicked = the_second_button_was_clicked
or:
def the_first_button_was_clicked(mainWinInstance):
# ...
mainWinInstance.the_second_button_was_clicked = the_second_button_was_clicked
mainWinInstance.button2.clicked.connect(mainWinInstance.the_second_button_was_clicked)
In both cases the instance attribute has to be created before the connection (which also means before calling the first function in the first case).
Consider that this "monkey patching" approaches should only be used in special cases (mostly due to objects that cannot be subclassed because created autonomously), especially if done outside the class or even the script.
In most cases, what you're doing is considered bad practice, and if you're doing this with a class created on your own, there's probably something really wrong in your implementation: you should better rethink your logic and implement everything within the class itself.

Related

How to access self object within class from outside

I am writing an application that uses a Qt GUI and am now trying to multithread it (first time learner). A longer task will be contained within the worker thread eventually but output logs will be required to be written as it goes. The GUI class has a method to output these logs to a plain text widget. Up until now, everything has been running within the GUI class.
I currently have the following code (included the important bits for brevity):
class Worker(QRunnable):
#pyqtSlot()
def run(self):
Ui.logentry(self, "Test")
class Ui(QtWidgets.QMainWindow):
def __init__(self):
super(Ui, self).__init__()
uic.loadUi(resourcepath('./pycdra.ui'), self)
self.outputlog = self.findChild(QtWidgets.QPlainTextEdit, 'outputlog')
self.button = self.findChild(QtWidgets.QPushButton, 'button')
self.button.clicked.connect(self.Button)
self.threadpool = QThreadPool()
self.logentry("Available threads: %d" % self.threadpool.maxThreadCount())
def Button(self):
worker = Worker()
self.threadpool.start(worker)
def logentry(self, returntext):
self.outputlog.appendPlainText(self.timestamp() + " " + str(returntext))
self.outputlog.repaint()
def timestamp(self):
import datetime
ts = datetime.datetime.now(tz=None).strftime("%Y-%m-%d %H:%M:%S"))
return ts
def applic():
app = QApplication(sys.argv)
window = Ui()
window.show()
sys.exit(app.exec_())
applic()
When I try running this, the GUI loads perfectly, but upon pushing button the Ui.logentry part of Worker returns the error: AttributeError: 'Worker' object has no attribute 'outputlog'
I attempted making logentry() and timestamp() global so they can access and be accessed by both classes, but the closest I got with the line Ui.self.outputlog.appendPlainText(self.timestamp() + " " + str(returntext)) was that 'Ui' object has no attribute 'self'.
What am I missing? Am I right in making them global or are there other means to do this?
There are various problems with your code. I'll try to address them in order of importance.
logentry is an instance method of Ui, which means that it requires an instance of Ui in order to be run; what you're trying to achieve would never work since that self refers to an instance of Worker, which clearly doesn't have any outputlog attribute (which is what logentry expects instead). Remember: the self argument is not there just for fun, it always refers to the object (the instance, for instance methods) the function is called from; self.logentry means "call the function logentry using self as first argument. Since, in your case, self refers to an instance of Ui, that explains your main issue, since that instance doesn't have that attribute.
None is exactly what its name says: nothing. The timestamp function will throw another AttributeError, since there's no strftime attribute in None. That is part of a datetime object, so you have to get a now object, then call its strftime function against it. In any case, the tz argument requires a tzinfo subclass.
pyqtSlot only works for Qt classes that inherit from QObject (such as QWidget). QRunnable isn't one of those classes. You can check the whole inheritance tree in the header of the documentation in each class: if there's a "Inherits:" field, go up until there's none. If you get a QObject inheritance at some point, then you can use slots and signals for that object, otherwise not. Consider that: QWidget also inherits from QObject; all Qt widgets inherit from QWidget; there are Qt classes that inherit from QObject but are not widgets.
Even ignoring all the above, access to UI elements is always forbidden from external threads (including QRunnable objects); while you can theoretically (but unreliably) get their properties, trying to set them will most likely cause a crash; in order to change something in a UI element, using signals is mandatory. Note that "access" also includes creation, and always results in a crash.
Calling repaint is a common (and wrong) attempt to solve the above issue; that's unnecessary, as properly setting widget properties (like using appendPlainText()) already results in a scheduled repaint on its own; there are very few cases for which repaint is actually necessary, and the rule of thumb is that if you're calling it you probably don't know what your doing or why your doing it. In any case, calling update() is always preferred, and it must always be called from the main UI thread anyway.
Using imports in a function is rarely required, as import statements should always be in the very beginning of the script; while there are cases for which imports can (or should) be done later or in a specific function, doing them in a function that is likely to be called often, makes using them there completely pointless. Also, datetime is part of the standard library, so importing it on demand will hardly affect performance (especially considering its "performance weight" against what a big library like Qt is compared to it).
When the ui is loaded from a .ui file (or a pyuic generated file), PyQt alread creates all widgets as instance attributes, so there's no need for findChild. Unfortunately there are a lot of tutorials that suggest that approach, and they are just completely and plain wrong. You can already access those widgets as self.outputlog and self.button right after uic.loadUi.
Function names (like variables and attributes) should always begin with a lower case letter, as only classes and constants should begin with upper cases (see the official Style Guide for Python Code). Also, object names should always explain what those object do (see "self-documenting code"): a function that does an "action" should have a verb; if it's named "Button" it doesn't tell me that it's going to do some processing, and that's not a very good thing.
A "main" function (like your applic) usually makes sense within the common if __name__ == '__main__': block, which ensures that that function doesn't get called in case the file gets imported instead of being directly run. (See this answer and the related question).
Since QRunnable doesn't inherit from QObject, we can create a QObject subclass that acts as a signal "proxy", and make it a member of the QRunnable instance. Then we must connect to that signal everytime we create a new Worker object.
Here is a revised version of your code, based on the above points.
import datetime
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
class WorkerSignals(QObject):
mySignal = pyqtSignal(str)
class Worker(QRunnable):
def __init__(self):
super().__init__()
self.signalProxy = WorkerSignals()
self.mySignal = self.signalProxy.mySignal
def run(self):
self.mySignal.emit("Test")
class Ui(QMainWindow):
def __init__(self):
super(Ui, self).__init__()
loadUi('./pycdra.ui', self)
self.button.clicked.connect(self.startWorker)
self.threadpool = QThreadPool()
self.logentry("Available threads: %d" % self.threadpool.maxThreadCount())
def startWorker(self):
worker = Worker()
worker.mySignal.connect(self.logentry)
self.threadpool.start(worker)
def logentry(self, returntext):
self.outputlog.appendPlainText(self.timestamp() + " " + str(returntext))
def timestamp(self):
ts = datetime.datetime.now()
return ts.strftime("%Y-%m-%d %H:%M:%S")
def applic():
import sys
app = QApplication(sys.argv)
window = Ui()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
applic()
I suggest you to carefully study the provided code and the differences with yours, and then do some careful, patient research both on the links given above and the following topics:
classes and instances, and the meaning of self;
python types (including None);
what is event driven programming and how it relates with graphical interfaces;
the most important Qt classes, QObject and QWidget, and all their properties and functions (yes, they are a lot);
general PyQt related topics
(most importantly, signals/slots and properties);
code styling and good practices;
Use the class' initialised form
class foo:pass
selfuotsideclass=foo()
Use variable selfoutsideclass as self

How do I create GUI classes for windows, which have subwindows/classes that can access to the main GUI's functions?

How do I create GUI classes for windows which have subwindows/classes that can access the main GUI's functions?
I have the below code which modifies the compiled .ui code from designer. What I want it to do is, when clicking the top-right "X", or using File -> Exit function, to close the window comprising the Window_SecondWindow class, and show the main window again--effectively calling the main window's show() from the subclass. I want to show only one window at a time.
When the code is run as-is, the Window_SecondWindow class hides, but immediately shows again, leading me to believe super is acting as self.
from PyQt5 import QtWidgets
from GUI import compiled_MainWindow
from GUI import compiled_SecondWindow
class Window_MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.ui = compiled_MainWindow.Ui_MainWindow()
self.ui.setupUi(self)
self.ui.closeEvent = self.clicked_EXIT
# connect widgets
self.ui.Btn.clicked.connect(self.clicked_Btn)
self.ui.actionExit.triggered.connect(self.clicked_EXIT)
# add windows
self.SecondWindow = SecondWindow()
# more windows attached to main window
def clicked_Btn(self):
self.hide()
self.SecondWindow.show()
def clicked_EXIT(self):
self.close()
class Window_SecondWindow(Window_MainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.ui = compiled_SecondWindow.Ui_MainWindow()
self.ui.setupUi(self)
self.ui.closeEvent = self.clicked_EXIT
self.ui.actionExit.triggered.connect(self.clicked_EXIT)
def clicked_EXIT(self):
self.hide()
super().show()
Before answering your question, I'd like to address some important aspects.
First of all, never edit the generated code from pyuic to create your programs. They are intended to be used as imported modules, mostly as "resources": you import and integrate them into your code, but you should always leave them as they are. See the documentation on using Designer for more insight about this.
Be careful in overriding functions within the __init__: some functions are not "virtual" (thus, cannot be overwritten in such a way) and in some cases Qt always calls the base class function name anyway; just overwrite the method and call the base class implementation with super() if required. Also, closeEvent has the close event as a mandatory argument, and you have to add that to your overridden function, even if you don't use it (in the following examples I'm just using *args). That said, you should never use an overridden function as a slot that has a different argument, or viceversa.
Finally, you should not use capitalized names for attribute and variable names, as it is confusing and prone to errors (capitalization is mostly used for class names only, not their instancies).
Now, the answer
You are almost right, super() acts "as self", in the sense that it just calls the inherited show() method of the class against the instance. So, it calls the show method of Window_MainWindow, but since the instance is the second window, it's the same as doing Window_MainWindow.show(self), with self being the Window_SecondWindow instance; it is exactly as doing self.show().
There are two (and a half) possibilities.
The first, more obvious solution, is to give a reference of the main window instance to the second one:
class Window_MainWindow(QtWidgets.QMainWindow):
def __init__(self):
# ...
self.secondWindow = Window_SecondWindow()
self.secondWindow.mainWindow = self
class Window_SecondWindow(Window_MainWindow):
# ...
def clicked_EXIT(self, *args):
self.hide()
self.mainWindow.show()
Be aware that while, as #noras points out in the comment, you could set the main window as a parent in the init argument, but this only works as expected with QMainWindow and QDialog descendants; if the child widget is of any other kind, it will be shown inside the parent, not as a separate window.
The second (and more "Qt-wise correct") is to create a signal for the second class that is emitted when it's closed, and connect it in the main window so that it's shown again when that happens:
class Window_MainWindow(QtWidgets.QMainWindow):
def __init__(self):
# ...
self.secondWindow = Window_SecondWindow()
self.secondWindow.closed.connect(self.show)
class Window_SecondWindow(Window_MainWindow):
closed = QtCore.pyqtSignal()
def clicked_EXIT(self, *args):
self.hide()
self.closed.emit()
The second-and-a-half solution is to use an event filter:
class Window_MainWindow(QtWidgets.QMainWindow):
def __init__(self):
# ...
self.secondWindow = Window_SecondWindow()
self.secondWindow.installEventFilter(self)
def eventFilter(self, source, event):
if source == self.secondWindow and event.type() == QtCore.QEvent.Close:
self.show()
return super().eventFilter(source, event)

Why is my python class inheritance incorrect?

I'm learning to use PyQt5 and have run across a problem. My code is attempting to just draw a simple black box in the QMainWindow object by writing a second class PaintWidget which inherits from QWidget. I've posted my code first, and the correct one below it.
class PaintWidget(QWidget):
def __init__(self):
super().__init__()
self.qp = QPainter()
self.initUI()
def initUI(self):
self.qp.fillRect(1,1,100,100, Qt.black)
Correct:
class PaintWidget(QWidget):
def paintEvent(self, event):
qp = QPainter(self)
qp.fillRect(1, 1, 100, 100, Qt.black)
This is what confuses me. In order to create this class, we need to inherint from the super class QWidget, inorder to do so we use the function super().__init__() under __init__(self). We then set up the QPaint object which we will use in our method initUI() which actually does the work. Now this doesn't work when I run it.
The second, correct class, doesn't even seem to inherent, since it has no super().__init__(), even worse, it is setting up a method that is never even called (paintevent(self, event)), which takes an argument that seemingly comes from nowhere. Can someone point out why I'm wrong?
There is absolutely no difference to inheritance between the two cases. In both cases you say class PaintWidget(QWidget), so you are inheriting the QWidget.
The difference is in where you draw. In constructor (__init__), the widget is not yet mapped to the screen, so if you try to draw there, it won't have effect.
When the widget is actually displayed on screen, the system will invoke the paintEvent, which is a virtual method of the QWidget, and that is where you must draw the content. You only define that method in the second example.
Note that you need fresh QPainter in each invocation of the paintEvent. Creating one in the constructor and then using it in paintEvent would not work.
Also, most windowing systems don't remember the content of the widget when it is not actually visible on screen and rely on being able to call the paintEvent whenever the widget becomes visible again. So the method will likely be called many times. In contrast, the constructor, __init__, is only called once when creating the object.

Why does __init__() have to be used twice when I inherit from another class?

I apologize if the question is not a correct statement about what is going on or it turns out to be specific for the example that I describe. It is just what I noticed. I have been learning how to make GUIs using Tkinter in Python 2.7 and I have followed several tutorials, and I have seen several different styles for structuring the code.
One way is the following:
import Tkinter as tk
root = tk.Tk()
root.title("My App")
root.mainloop()
The other way I have seen is:
import Tkinter as tk
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
tk.Tk.title("My App")
root = App()
root.mainloop()
The second method creates a class App that inherits from the tk.Tk class, thus making App a subclass of tk.Tk? def __init__(self): is the constructor for class App I am defining. But then I must also call the __init__() function from the tk.Tk class as well. If that is true, why is that? When I just run root = tk.Tk(), its __init__() function is called then?
Yes, when you run root=tk.Tk() then an instance of the class tk.Tk is instantiated -- which means calling the __init__ of this class.
In the second method you want to create a new class -- which might be useful especially in a larger project, to be able to port it anywhere else.
You cannot append something to the parent's __init__ method, you can just override it by defining it anew. So if you still want all the useful stuff to happen, which is executed in the tk.Tk.__init__(), you have to call it explicitly.
One might argue, that a better style would be to use super() instead of hardcoding the parent class name. But this gets relevant in still more complicated projects...
When you create a class object, it's constructor gets called automatically. This is what is happening in both snippets. The first one instantiates an object for the Tk class so therefore the __init__ method for the Tk class gets called. Where in the second way, you are not creating an object for the Tk class. You are creating an object for your App class. This does not mean it will call the constructor for the class that it has inherited from. You need to call it explicitly.

Python: RuntimeError: super-class __init__() of %S was never called

I tried to do some operation (setParent) on an object in Python (an instance of a class which inherits from a different class - to be specific, QtGui.QLabel), but during runtime the above error was raised. The object itself has had some fields with actual content (verified on debug), but from some reason I couldn't "use" it. What does the error mean and how can I fix it? For some additional information, I shall say that the object was returned from a static method before I tried to do this operation on it.
The subclass has a __init__() function of its own:
def __init__(self, image, father):
super(AtomicFactory.Image, self).__init__(father)
self.raw_attributes = image.attributes
self.attributes = {}
father.addChild(self)
self.update()
Now I wrote a similar code, a simple one, that had the same error on the line widget.setParent(mw) when the window was moved.
#!/usr/bin/env python
import sys
import copy
from PyQt4 import QtCore, QtGui
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
main_widget=QtGui.QWidget()
widget = QtGui.QPushButton('Test')
widget.resize(640, 480)
widget.setParent(main_widget)
widget.move(0, 0)
widget2=QtGui.QPushButton('Test2')
widget2.i=0
widget2.resize(600, 200)
widget2.setParent(main_widget)
widget2.move(640, 0)
def onResize(event):
print event
mw=copy.deepcopy(main_widget)
widget.setParent(mw)
widget2.setParent(mw)
widget.move(0, 0)
widget2.move(640, 480)
main_widget_width=main_widget.width()
widget_width=widget.width()
width2=main_widget_width-widget_width
height2=widget2.height()
widget2.resize(width2, height2)
widget2.move(640, 0)
main_widget.resizeEvent=onResize
def onClick():
size=(widget2.width(), widget2.height())
if(widget2.i%2==0):
widget2.resize(int(size[0]/2), int(size[1]/2))
else:
widget2.resize(size[0]*2, size[1]*2)
widget2.i+=1
QtCore.QObject.connect(widget, QtCore.SIGNAL('clicked()'), onClick)
main_widget.show()
sys.exit(app.exec_())
What was the problem?
If you want to inherit QObject (or QWidget), you must always call the super-class __init__:
class MyObject(QObject):
def __init__(self, *args, **kwargs):
super(MyObject, self).__init__(arguments to parent class)
#other stuff here
You may also call the parent's class's __init__ after some instructions, but you can't call QObject methods or use QObject attributes until you did so.
Edit:
In your case you are trying to deepcopy a QWidget, but this is not possible.
Python may be able to copy the wrapper of the QWidget, but the QWidget itself is a C++ object that python cannot handle with the default implementation of copy.deepcopy, hence whenever you call a method of the copied instance you get the RuntimeError because the underlying C++ object wasn't initialized properly.
The same is true for pickling these objects. Python is able to pickle the wrapper, not the C++ object itself, hence when unpickling the instance the result is a corrupted instance.
In order to support deepcopy() the QWidget class should implement the __deepcopy__ method, but it does not do that.
If you want to copy widgets you'll have to implement by yourself all the mechanism by hand.

Categories