PyQt4 - Custom widget class structure? - python

During regular intervals of my program, a block (of 3 stacked) widgets need to be added to a horizontal layout. Since the widgets within each block are important to eachother, I wish to encapsulate each stack as it's own widget (making the layout adding business much easier).
I'm having trouble getting PyQt4 to recognise my 'stack' as a widget.
I made the widget stack in Qt Designer (as form: widget) and converted it to a .py via
'pyuic4 DesignerFile.ui > ClassFile.py'.
Now I can't seem to add this 'stack' (parent widget of 3 child widgets) to the layout via .addWidget( Class ).
I tried constructing a super class of the stack class (because I need to add more functionality to the stack) but the instance of the class is either...
Not recognised as a widget
Invisible
defective because I've no idea on how to structure the super class.
Here's what I'm failing with at the moment (though it's about the 8th class structure I've tried):
from ClassFile import ClassCode
class Stack(ClassCode):
def __init__(self,parent= None):
QtGui.QWidget.__init__(self,parent)
Could somebody help me structure this or lead me to some good examples?
(I've mimicked the code in both the following sources but with no avail!!
http://lateral.netmanagers.com.ar/stories/27.html#what-you-need-to-follow-the-tutorial
http://zetcode.com/tutorials/pyqt4/customwidgets/ )
Thanks!
Specs:
python 2.7.2
PyQt4
Windows 7

When you compile a python module from a ui file with the default options, it will (amongst other things) generate a simple "setup" class. In outline, the setup class will look like this:
class Ui_ClassCode(object):
def setupUi(self, ClassCode):
ClassCode.setObjectName("ClassCode")
# bunch of boiler-plate ui code goes here
self.retranslateUi(ClassCode)
QtCore.QMetaObject.connectSlotsByName(ClassCode)
def retranslateUi(self, ClassCode):
pass
There are a couple of issues to notice here that are relevant to the question.
Firstly, the setup class is designed to be used as a mixin rather than as a direct subclass. It's task is to "inject" ui into a host widget that is passed to the setupUI method.
Secondly, the setup class is given an ugly, unpythonic identifier that is created by prepending "Ui_" to the objectName property that was set in Designer.
Fortunately, pyuic4 provides a way to bypass these two issues. All that's required is to use the -w option when compiling the python module from the ui file:
pyuic4 -w designerfile.ui > classfile.py
This will add a wrapper class that (1) can be easily subclassed, and (2) has the class-name that you damn well gave it in Qt Designer.
The wrapper class will look something like this:
class ClassCode(QtGui.QWidget, Ui_ClassCode):
def __init__(self, parent=None, f=QtCore.Qt.WindowFlags()):
QtGui.QWidget.__init__(self, parent, f)
self.setupUi(self)
As you can see, it doesn't do anything special: you could easily replicate what it does in your own code. But, IMO, it does make the compiled modules much more intuitive to use.
For example:
from PyQt4 import QtGui, QtCore
from classfile import ClassCode
class Stack(ClassCode):
def __init__(self, parent=None):
ClassCode.__init__(self, parent)
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.stack = Stack(self)
self.setCentralWidget(self.stack)

First, it's more appropriate to call the parent __init__ with the use of super. That will ensure the method in the proper super class is invoked. Second, when using a class constructed with pyuic, you need to call self.setupUi(self) from your __init__ method. And lastly, you need to make sure and multiple inherit from both the proper Qt class and the pyuic generated class (which is really more of a mixin).
So, something like this:
from ClassFile import ClassCode
class Stack(QtGui.QWidget, ClassCode):
def __init__(self,parent= None):
super(Stack, self).__init__(parent)
self.setupUi(self)

Related

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)

Port C++ class to PyQt

I am trying to convert a Qt4 custom widget written in C++ to a Python 2.7 custom widget. However, I have not been able to figure out how QLabel(parent) would be written in Python. This is the original C++ code from the ".ccp" file:
DocumentWidget::DocumentWidget(QWidget *parent)
: QLabel(parent)
{
currentPage = -1;
setAlignment(Qt::AlignCenter);
}
The QLabel(parent) seems to be some sort of initializer list. I've tried using multiple inheritance in Python in parallel, but this leads to the following error: Cannot create a consistent method resolution order (MRO) for bases QLabel, QWidget.
I'm trying to port the code instead of creating a wrapper for the C++ widget, because I don't know C++ and think I will have to customize the widget further in the future.
I'm not trained as a programmer and this is the first day I ran into C++, so feel free to correct me even if I'm doing something silly. I will not feel embarrassed.
The code defines a constructor for the DocumentWidget class, which inherits QLabel and requires a QWidget as parent.
The equivalent PyQt code would be:
from PyQt4 import QtCore, QtGui
class DocumentWidget(QtGui.QLabel):
def __init__(self, parent):
super(DocumentWidget, self).__init__(parent)
# or QtGui.QLabel.__init__(self, parent)
self.currentPage = -1
self.setAlignment(QtCore.Qt.AlignCenter)
Multiple inheritance worked, but the base classes had to be called in the correct order (i.e., DocumentWidget(QLabel, QWidget) instead of DocumentWidget(QLabel, QWidget)).
In full:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class DocumentWidget(QLabel, QWidget):
def __init__(self, parent=None):
super(DocumentWidget, self).__init__()
self.currentPage = -1
self.setAlignment(Qt.AlignCenter)

Different ways of using __init__ for PyQt4

So... I'm working on trying to move from basic Python to some GUI programming, using PyQt4. I'm looking at a couple different books and tutorials, and they each seem to have a slightly different way of kicking off the class definition.
One tutorial starts off the classes like so:
class Example(QtGui.QDialog):
def __init__(self):
super(Example, self).__init__()
Another book does it like this:
class Example(QtGui.QDialog):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
And yet another does it this way:
class Example(QtGui.QDialog):
def__init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
I'm still trying to wrap my mind around classes and OOP and super() and all... am I correct in thinking that the last line of the third example accomplishes more or less the same thing as the calls using super() in the previous ones, by explicitly calling the base class directly? For relatively simple examples such as these, i.e. single inheritance, is there any real benefit or reason to use one way vs. the other? Finally... the second example passes parent as an argument to super() while the first does not... any guesses/explanations as to why/when/where that would be appropriate?
The first one simply doesn't support passing a parent argument to its base class. If you know that you'll never need the parent arg, that's fine, but this is less flexible.
Since this example only has single inheritance, super(Example, self).__init__(parent) is exactly the same as QtGui.QDialog.__init__(self, parent); the former uses super to get a "version" of self that calles QtGui.QDialog's methods instead of Example's, so that self is automatically included, while the latter directly calls the function QtGui.QDialog.__init__ and explicitly passes the self and parent arguments. In single inheritance there's no difference AFAIK other than the amount of typing and the fact that you have to change the class name if you change inheritance. In multiple inheritance, super resolves methods semi-intelligently.
The third example actually uses QWidget instead of QDialog, which is a little weird; presumably that works because QDialog is a subclass of QWidget and doesn't do anything meaningful in its __init__, but I don't know for sure.

PyQt - subclassing the QMainWindow to access Gui elements

I use a QStackedWidget and switch between different views. Each pane is basically a class and should reside in it's own file.
The problem is I want to access a QTableView from the other file without passing it's reference into the constructor.
Main File:
class MyApp(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyApp, self).__init__(parent)
self.setupUi(self)
2nd File
from ui_MainWindow import Ui_MainWindow
class LimitsEditor(QMainWindow):
def __init__(self, session):
QMainWindow.__init__(self)
self.tblCommonLimits_horizheader = QHeaderView(Qt.Horizontal)
self.tblCommonLimits_horizheader = QMainWindow.tblLimits.horizontalHeader()
I get this error:
AttributeError: type object 'QMainWindow' has no attribute 'tblLimits'
As you can see, I want to access a table called "tblLimits" that I created in QtDesigner, but I'm unable to get access to it in my second file.
Any suggestions?
(edit for formatting)
I am editing this to show what I am doing that works:
In the main, when instantiating the class:
self.LimitsEditor = LimitsEditor(self.ui.tblLimits)
In the LimitsEditor file:
class LimitsEditor():
def __init__(self, tblLimits):
self.tblLimits = tblLimits
Now in the main I can access the table as either 'self.ui.tlbLimits' OR 'self.LimitsEditor.tblLimits'
This is how I have been doing it, and it works fine. It just didn't seem quite right to me, so I was wondering if there was a way to just inherit the knowledge of all the UI elements into another class/subclass.
If what you are trying to do is to have LimitsEditor be able to access the exact same table instance being used by MyApp, then this approach you are trying is impossible. The .ui file is a description of a layout of widgets which you apply to your class. When you call setupUi() inside your QMainWindow class, it creates instances. The actual UI module does not contain any references to these instances that you can then access in another file.
You must share a reference to the instance from MyApp to LimitsEditor. This comes down to a design decision. Here are a few suggestions (since I don't know how your app is really organized)
Wherever you are managing your stacked widget, you can pass a reference of the table instance to your LimitsEditor
Let your LimitsEditor be unaware of the table widget, and emit signals, to which your parent objects will listen and manage the table instance in response
Set up your LimitsEditor with an eventsFilter for the table (in your parent object). Your LimitsEditor wont directly have a reference to the table, but rather will receive events for it that it can handle.
Referring to the exception that you are seeing, QMainWindow is the PyQt4 class and does not contain your custom child widgets. Those are located on the instance of your custom class which contains the setupUi() call. You would then need to access it via self.tblLimits, but again this would be only for the class that actually used the Ui file, not other random classes.
When working with the QtDesigner in PyQt you usually follow the same patter:
Create the designer .ui file.
Create a class to use it.
Ensure that the ui file sets the widgets of your class.
For example:
class MyApp(QMainWindow):
def __init__(self, parent=None):
super(MyApp, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
class LimitsEditor(QMainWindow):
def __init__(self, session):
super(QMainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.tblCommonLimits_horizheader = QHeaderView(Qt.Horizontal)
self.tblCommonLimits_horizheader = self.ui.tblLimits.horizontalHeader()
Make sure you do access the widget through the instance ui element.

replacing widget at runtime

Here is the situation. I have a class which is derived from a QListView that adds some convenience functions, a custom widget if you like. I do not want to wrestle with the Designer to use my widget. I simply want to use a plain QlistView in the Designer (as a placeholder) and compile it with pyuic4. At runtime I want to replace that normal QListView with my own version.
How can you do this?
I was hoping something like this in the init would do the trick:
self.lstView1 = MyListView
but it doesn't...
The problem is that you are actually simply replacing the object pointed by lstView1 but not adding it to the widget. That is, when you create you object you simply tell python to point to your new object using lstView1 but the actual UI is using the old pointer since it as already added.
I'm going to assume that you have use py4uci to convert the ui files to python and you set up the gui as:
class ExambleUI(QtGUi.QDialog, UI_Example):
def __init__(self, parent):
QtGui.QDiialog.__init__(self, parent)
self.setupUI(self)
self.lstView1 = MyListView
Because setupUi is executing before you change the value of lstView, you are not getting the new widget. You just have to swap the lines:
class ExambleUI(QtGUi.QDialog, UI_Example):
def __init__(self, parent):
QtGui.QDiialog.__init__(self, parent)
self.lstView1 = MyListView
self.setupUI(self)
On the other hand I recommend you to follow this tutorial and create and use you widget in the designer, it is easy and faster.
Use QLayout replace function:
ui->main_layout->replace(oldWidget, newWidget);

Categories