Wizard-like user interface with buttons next and back - python

I'm developing an application using the Qt Designer and PyQt4, I need to make several screens where each screen I capture user-specific data, for that I need to implement a next button and a back button similar to
where the current screen closes and the following opens when the user clicks next or if he clicks back, the screen closes and opens the previous screen, I made an example with only the next buttons and back to exemplify, if I was not clear:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Frm(QWidget):
def __init__(self, parent = None):
super(Frm, self).__init__(parent)
next = QPushButton('Next >', self)
back = QPushButton('< Back', self)
hbox = QHBoxLayout()
hbox.addWidget(back)
hbox.addWidget(next)
self.setLayout(hbox)
if __name__ == '__main__':
import sys
root = QApplication(sys.argv)
app = Frm(None)
app.show()
root.exec_()
In short: How do I implement a function that calls another screen and close the current at the click of a button?

First about a misconception: you do usually not create/show one screen (window) and close another, you usually only exchange the content of a wizard-like dialog window upon actions like pressing the buttons. The window is alive the whole time until the multiple page task is finished.
So I take it your question is really about:
How to exchange a widget in a layout?
Since you may still use PyQt4 which does not yet have QLayout.replaceWidget, it's best to just use methods removeWidget and addWidget of QLayout and since addWidget adds a widget to the end of the layout items list, I prefer a dedicated layout just for the interchangeable content of your wizard (see also: How to add an Item to the specific index in the layout).
Example code using PyQt5 but easily transferrable to PyQt4. Only the next button is implemented.
from PyQt5 import QtWidgets
class MyWizard(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# vertical layout, wraps content layout and buttons layout
vertical_layout = QtWidgets.QVBoxLayout()
self.setLayout(vertical_layout)
# content widget and layout
self.content_layout = QtWidgets.QVBoxLayout() # could be almost any layout actually
self.content = QtWidgets.QLabel('Page1') # customize with your content
self.content_layout.addWidget(self.content)
vertical_layout.addLayout(self.content_layout)
# back, forward buttons wraped in horizontal layout
button_layout = QtWidgets.QHBoxLayout()
button_layout.addStretch()
back_button = QtWidgets.QPushButton('Back')
back_button.clicked.connect(self.back_button_clicked)
button_layout.addWidget(back_button)
forward_button = QtWidgets.QPushButton('Forward')
forward_button.clicked.connect(self.forward_button_clicked)
button_layout.addWidget(forward_button)
vertical_layout.addLayout(button_layout)
def back_button_clicked(self):
"""
The back button is clicked.
"""
pass
def forward_button_clicked(self):
"""
The forward button is clicked.
"""
# remove old content
self.content_layout.removeWidget(self.content)
self.content.deleteLater()
# create new content
self.content = QtWidgets.QLabel('Another Page')
# add new content
self.content_layout.addWidget(self.content)
app = QtWidgets.QApplication([])
wizard = MyWizard()
wizard.setWindowTitle('MyWizard Example')
wizard.setFixedSize(600, 400)
wizard.show()
app.exec_()
And it looks like:
However, as already written in the comment by Marius, there is quite extensive support for such dialogs in Qt using QWizard. So I strongly recommend to use that instead. The example above is only to demonstrate the ability of inserting and removing widgets in layouts.
You should definitely use QWizard for such problems!

There is a QWizard class that allows you to create wizards in Qt and PyQt. It implements all the functionality you want, and lots more. All you do is design your pages by extending QWizardPage, and add them to the wizard. This is much simpler than doing the whole thing from scratch as you propose.

Old question but missing example with existing API
You don't need to create all structure of an Wizard by yourself. Qt (and PyQt) already provides a class called QWizard.
Basic example:
wizard = QtWidgets.QWizard()
page1 = QtWidgets.QWizardPage()
page1.setTitle('Page 1 is best!')
page1.setSubTitle('1111111111')
lineEdit = QtWidgets.QLineEdit()
hLayout1 = QtWidgets.QHBoxLayout(page1)
hLayout1.addWidget(lineEdit)
wizard.addPage(page1)
Complete example and some explanation:
https://www.youtube.com/watch?v=kTJ1QULxXjg
https://impatientprogrammer.net/2018/07/06/pyside-pyqt-qwizard-in-3-minutes/

Related

How Refresh/Re-initialize Widgets in QStackedWidget

I'm trying to create a script that makes API calls to a website to get info (via the requests module).
The user can then manipulate the website using my script/gui.
My app's main window will have several buttons at the bottom which acts like tabs to switch between windows(let's say for argument's sake 2 buttons to switch between two windows).
When certain changes are made, I need the QStackedWidget to refresh all the widgets/labels in certain windows that are not currently being displayed.
Summary of my code:
# Global Variables
app = QApplication(sys.argv)
win = QtWidgets.QStackedWidget()
response = {} # global dict to store API response from website
class UiWindowOne(QMainWindow):
# This window mostly shows information that I get from the website.
def __init__(self):
super(UiWindowOne, self).__init__()
self.setup_ui(self)
self.retranslate_ui(self)
# Then I map buttons to methods
def setup_ui(self, WindowOne):
# This was generated by QT Designer and places widgets
def retranslate_ui(self, WindowOne):
# This was generated by QT Designer and places widgets
def refresh(self):
'''
This function refreshes the current window. Basically, I put everything in the __init__ function in here (except "super(UiWindowOne, self).__init__()".
:return: None
'''
self.setup_ui(self)
self.retranslate_ui(self)
# Also map buttons to methods
class UiWindowTwo(QMainWindow):
def __init__(self):
super(UiWindowTwo, self).__init__()
self.setup_ui(self)
self.retranslate_ui(self)
# Then I map buttons to methods
def setup_ui(self, WindowTwo):
# This was generated by QT Designer
def retranslate_ui(self, WindowTwo):
# This was generated by QT Designer
def refresh(self):
'''
This function refreshes the current window. Basically, I put everything in the __init__ function in here (except "super(UiWindowTwo, self).__init__()".
:return: None
'''
self.setup_ui(self)
self.retranslate_ui(self)
# Also map buttons to methods
def update_website(self):
# Make changes to website
# After changes were made, I want to get modified info from the website and re-initialize/refresh both windows to reflect the changes made.
# I can easily call self.refresh() to refresh WindowTwo. But I cannot refresh WindowOne from here.
def main():
# Here I make API calls to the Website to get info/images
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(".\\imgs/static/A.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
win.setWindowIcon(icon)
win.setWindowTitle("NAME")
first_window = UiWindowOne()
second_window = UiWindowTwo()
win.addWidget(first_window)
win.addWidget(second_window)
win.setGeometry(250, 250, 820, 854)
win.setFixedWidth(820)
win.setFixedHeight(854)
win.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
I have tried doing a "first_window.refresh()" under the update_website() function in UiWindowTwo, but then python tells me that first_window is not defined.
I then tried making first_window and second_window global variables, but then I ended up reordering my whole script and couldn't get it to run.

How to transfer date selection from calendar widget to QLineEdit

I'm playing around with PyQt5 (which I just started learning yesterday).
I'm trying to create a window/layout, with two entry boxes (to enter 'start' and 'end' dates), so that when each one is clicked, the QCalendarWidget is triggered to popup, and when the user selects the date, the date is entered into the QLineEdit field.
So far, it simply shows a blank window, but I'm not sure what I'm doing wrong.
class selectedDate(QWidget):
def __init__(self):
super(selectedDate, self).__init__()
self.layout = QVBoxLayout(self)
self.selection = QLineEdit("Click to Enter Date", self)
self.layout.addWidget(self.selection)
self.layout.addWidget(self.selection)
self.selection.installEventFilter(self)
def mousePressEvent(self, e):
self.myCal()
super(selectedDate, self).mousePressEvent(e)
def eventFilter(self, object, e):
if self.layout.indexOf(object) != -1:
if e.type() == e.MouseButtonPress:
pass
return super(selectedDate, self).eventFilter(object, e)
def myCal(self):
self.cal = QCalendarWidget(self)
self.cal.setGridVisible(True)
self.cal.move(10, 20)
self.cal.clicked[QDate].connect(self.showDate)
self.date = self.cal.selectedDate()
self.selection.setText(self.date.toString())
self.setGeometry(300, 300, 415, 350)
self.setWindowTitle('Calendar')
self.show()
def showDate(self, date):
self.selection.setText(date.toString())
app = QApplication(sys.argv)
top = selectedDate()
app.exec_()
There's quite a lot of issues, let's work through some.
To see a window, you need to call QWidget.show(). Here you only call self.show() in myCal method. But myCal is only called with a mouse click. Surely you want to display the window right after starting the application. To do that you can simply put self.show() at the end of the __init__ method.
class SelectedDate(QWidget):
def __init__(self):
# layout stuff, QLineEdit, etc
self.show() # show your first window with the QLineEdit
Next, the mouse press event. The method mousePressEvent is actually never called! You can check that by adding a print statement in it.
It should be called when a MouseButtonPress is detected (in eventFilter)
Finally the calendar widget. We want to open it in a new window (QCalendarWidget doesn't open as a pop up by default, you need to do it yourself).
def myCal(self):
self.cal = QCalendarWidget(self)
self.cal.setGridVisible(True)
self.cal.clicked[QDate].connect(self.showDate)
# create a new window that contains the calendar
self.calendarWindow = QWidget()
hbox = QHBoxLayout()
hbox.addWidget(self.cal)
self.calendarWindow.setLayout(hbox)
self.calendarWindow.setGeometry(300, 300, 415, 350)
self.calendarWindow.setWindowTitle('Calendar')
# open this new window
self.calendarWindow.show()
Now some more advice. You should start by a simple app and build more functionality when it works. Writing a lot of code for only a blank window it not a good idea! So if you where to do this again, work by steps:
Show a window with a QLineEdit (write code, test that it works)
Implement the event filter (use print statements to see if it works)
Implement opening a new blank window when clicking the QLineEdit
Fill that blank window with the calendar
Connect the calendar to the QLineEdit text (that code was good by the way)
Also, you can use better variable names, some suggestions:
selectedDate -> SelectDateWidget
selection -> date_selection
mousePressEvent -> on_date_selection_clicked
myCal -> open_calendar
cal -> calendar
showDate -> on_calendar_clicked or update_date_selection_text

UI made in QT Designer shifts behind Title Bar [duplicate]

I'm trying to create an application that contains a web browser within it, but when I add the web browser my menu bar visually disappears but functionally remains in place. The following are two images, one showing the "self.centralWidget(self.web_widget)" commented out, and the other allows that line to run. If you run the example code, you will also see that while visually the entire web page appears as if the menu bar wasn't present, you have to click slightly below each entry field and button in order to activate it, behaving as if the menu bar was in fact present.
Web Widget Commented Out
Web Widget Active
Example Code
import os
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
class WebPage(QWebEngineView):
def __init__(self, parent=None):
QWebEngineView.__init__(self)
self.current_url = ''
self.load(QUrl("https://facebook.com"))
self.loadFinished.connect(self._on_load_finished)
def _on_load_finished(self):
print("Url Loaded")
class MainWindow(QMainWindow):
def __init__(self, parent=None):
# Initialize the Main Window
super(MainWindow, self).__init__(parent)
self.create_menu()
self.add_web_widet()
self.show()
def create_menu(self):
''' Creates the Main Menu '''
self.main_menu = self.menuBar()
self.main_menu_actions = {}
self.file_menu = self.main_menu.addMenu("Example File Menu")
self.file_menu.addAction(QAction("Testing Testing", self))
def add_web_widet(self):
self.web_widget = WebPage(self)
self.setCentralWidget(self.web_widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.showMaximized()
sys.exit(app.exec_()) # only need one app, one running event loop
Development Environment
Windows 10, PyQt5, pyqt5-5.9
EDIT
The problem doesn't seem to be directly related to the menu bar. Even removing the menu bar the issue still occurs. That said, changing from showMaximized() to showFullScreen() does seem to solve the problem.
I no longer believe this is an issue with PyQt5 specifically but rather a problem with the graphics driver. Specifically, if you look at Atlassian's HipChat application it has a similar problem which is documented here:
https://jira.atlassian.com/browse/HCPUB-3177
Some individuals were able to solve the problem by running the application from the command prompt with the addendum "--disable-gpu" but that didn't work for my python application. On the other hand, rolling back the Intel(R) HD Graphics Driver did solve my problem. Version 21.20.16.4627 is the one that seems to be causing problems.

Qt - keep reference of widget in Python

In reference to a previous question, I need some help with keeping references in my application.
First a snippet from my code.
from PyQt4 import QtGui
import os, os.path
import sys
class mainWindowHandler():
equationEditor = []
_listview = None
_window = None
def __init__(self):
return
def showAddEquation(self):
"""Creates a new instance of the dynamic editor for adding an equation"""
#create a horizontal split layout
window = QtGui.QWidget()
layout = QtGui.QHBoxLayout()
current = len(self.equationEditor) - 1
de = QtGui.QPushButton(str(current))
self.equationEditor.append(de)
de.clicked.connect(self.clicked)
#fill list view with items from equation collection
listview = QtGui.QListWidget()
for equation in self.equationEditor:
item = QtGui.QListWidgetItem()
item.setText(equation.text())
listview.addItem(item)
layout.addWidget(listview)
layout.addWidget(de)
window.setWindowTitle("Equation {}".format(str(current))
window.setLayout(layout)
self._window = window
self._listview = listview
window.show()
return window
def clicked(self):
"""Method for handling the button events in the solver settings\n
signal = the button hit\n"""
return self.showAddEquation()
if __name__ == "__main__":
path = os.path.dirname(os.path.abspath(__file__))
app = QtGui.QApplication(sys.argv)
ewh = mainWindowHandler()
window = ewh.showAddEquation()
sys.exit(app.exec_())
The application will (later) create a window that allows the manipulation of certain settings - in my code example represented by the QPushButton. These settings are later written to a txt-file, but until then I save them in form of there widget. I simply add the widget to a collection and recall them from there. That works well on the Python-level.
Now, I have a button that creates a new instance of the window from inside of the window itself. That works too. But only until the third instance. At that point I loose the reference to my QPushButton on the Qt-level. I get the
wrapped C/C++ object of type `QPushButton` has been deleted
error when trying to retrieve the buttons from my collection (equationEditor). In Python they are still there, but obviously the corresponding Qt-objects where destroyed because I somewhere mishandled the references.
Can someone point out a better solution or how I can keep the references?
Thanks...
Edit:
As there seem to be some confusions I will try to explain the functionality a bit more in detail.
The program starts and creates a window "Equation 1" with a QListViewand a QPushButton "1". In the list view all available QPushButton are listed (at start only 1 item). In my actual program the QPushButton is QWidget with some text fields and the QPushButton.
If the user clicks "1" then the button "1" should disappear and a new instance of QPushButton named "2" should appear at the position of "1". Additionally, the listview should now hold two items "1" and "2" and the window should have the title "Equation 2". If it is a new window or the same as before with new contents is not relevant. Both variants would be okay. The former is the way it is implemented at the moment. Visible should by only one window at a time.
All instances of QPushButton should by collected in a small list (called equationEditor) to keep them in the memory. In my actual program this is used for saving all changes made in the widgets without writing the changes to a temp file.
Later, if the user selects item "1" in the QListView then the current visible QPushButton should be replaced by the QPushButton "1" (from the collection equationEditor) or if he selects the second item the QPushButton "2" should be shown.
Why?
The widget that will be used later contains a lot of editable data. As the user could edit that at any time it is easier to keep the widgets in memory without showing them instead of repopulating all the data again. As soon as the user selects one in the QListView the corresponding widget should be shown in the window so that he can edited the data in the widget again.
It's quite hard to understand what exactly you're trying to do. Looking at your code I wonder why it is even working twice before failing.
Btw. I just saw, that there is a quite accurate description of why it's failing in the previous post, given by Schollii
Anyways, I think you should make a new class for the equation window. The main class can then keep track of all opened windows in the equationEditor list. It can also add the values of the other opened windows to a new one, once created.
Here is how it would look like
from PyQt4 import QtGui
import os, os.path
import sys
class ShowAddEquation(QtGui.QWidget):
"""Creates a new instance of the dynamic editor for adding an equation"""
def __init__(self,parent=None):
super(ShowAddEquation, self).__init__(parent=parent)
#create a horizontal split layout
layout = QtGui.QHBoxLayout()
self.current = 0
self.de = QtGui.QPushButton(str(self.current))
self.listview = QtGui.QListWidget()
layout.addWidget(self.listview)
layout.addWidget(self.de)
self.setWindowTitle("Equation Editor")
self.setLayout(layout)
self.show()
def setCurrent(self, current):
self.current=current
self.de.setText(str(self.current))
class mainWindowHandler():
equationEditor = []
def __init__(self):
return
def clicked(self):
se = ShowAddEquation()
self.equationEditor.append(se)
se.de.clicked.connect(self.clicked)
current = len(self.equationEditor) - 1
se.setCurrent(current)
for equation in self.equationEditor:
item = QtGui.QListWidgetItem()
item.setText(str(equation.current))
se.listview.addItem(item)
if __name__ == "__main__":
path = os.path.dirname(os.path.abspath(__file__))
app = QtGui.QApplication(sys.argv)
ewh = mainWindowHandler()
ewh.clicked()
sys.exit(app.exec_())
So, after understanding the approach given in the first answer I have solved my problem. Here is the working code
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 3 14:31:15 2016
"""
from PyQt4 import QtGui
from PyQt4 import QtCore
import os, os.path
import sys
class mainWindowHandler():
equationEditor = []
_listview = None
_window = None
def __init__(self):
return
def showAddEquation(self):
"""Creates a new instance of the dynamic editor for adding an equation"""
#create a horizontal split layout
self._window = QtGui.QWidget()
layout = QtGui.QHBoxLayout()
self._listview = QtGui.QListWidget()
layout.addWidget(self._listview)
self._listview.clicked[QtCore.QModelIndex].connect(self.changed)
self._window.setLayout(layout)
#populate the right side of the layout with a button
self.clicked()
self._window.show()
return self._window
def clicked(self):
"""Make a new button instance and add it to the window and the collection"""
window = self._window
layout = window.layout()
current = len(self.equationEditor) - 1
de = QtGui.QPushButton(str(current))
self.equationEditor.append(de)
de.clicked.connect(self.clicked)
#close the currently shown button
item = layout.takeAt(1)
if item is not None:
item.widget().close()
layout.addWidget(de)
#fill list view with items from material collection
item = QtGui.QListWidgetItem()
item.setText(de.text())
self._listview.addItem(item)
self._window.setWindowTitle("Equation Editor {}".format(str(current)))
def changed(self, index):
"""hide the object on the right side of the layout and show the button at position index in the collection"""
layout = self._window.layout()
item = layout.takeAt(1)
item.widget().close()
# insert the selected button from the collection
de = self.equationEditor[index.row()]
layout.insertWidget(1, de)
self._window.setWindowTitle("Equation Editor {}".format(str(index.row() - 1)))
de.show()
if __name__ == "__main__":
path = os.path.dirname(os.path.abspath(__file__))
app = QtGui.QApplication(sys.argv)
ewh = mainWindowHandler()
window = ewh.showAddEquation()
sys.exit(app.exec_())

Remove top level QMenu from QMenubar programmatically

I am working on a Python project that uses Qt Designer to build interface. when working on building a plugin capability, I was able to allow dynamic loading of user plugins and create a new QMenu item to add to the main menubar. The problem is that there seems to be no way of removing that top level QMenu once it is added to the main menubar. I researched/searched quite a bit on this topic and it seems that every solution related to this topic is for removing sub-menu items from a QMenu via removing its actions, not for removing that dynamically-added QMenu itself. I hope someone would point out this to be a simple thing, and provide a code snippet to demo how this is done.
Achayan's solution above crashes on python2 qt4 (Windows) for the deletion
Better way for it is to to use the clear function.
Adding to the solution above,
def removeMenu():
self.main_menu.clear()
Hope this will give you idea for what you upto. And I took some part from another post, which is same qmenu thing
import sys
# This is bad, but Iam lazy
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.main_menu = self.menuBar()
widget = QWidget()
self.menuList = []
layout2 = QVBoxLayout(widget)
self.menuButton = QPushButton("Add Menu")
self.menuRmButton = QPushButton("Remove Menu")
layout2.addWidget(self.menuButton)
layout2.addWidget(self.menuRmButton)
self.menuButton.clicked.connect(self.create_menu)
self.menuRmButton.clicked.connect(self.removeMenu)
self.setCentralWidget(widget)
def create_menu(self):
menu2 = self.main_menu.addMenu('Menu 1')
self.menuList.append(menu2)
Action1=QAction('Menu 1 0',self)
Action1.triggered.connect(self.action_1)
menu2.addAction(Action1)
Action2=QAction('Menu 1 1',self)
Action2.triggered.connect(self.action_2)
menu2.addAction(Action2)
def removeMenu(self):
if self.menuList:
for eachMenu in self.menuList:
menuAct = eachMenu.menuAction()
self.main_menu.removeAction(menuAct)
# just for safe side
menuAct.deleteLater()
eachMenu.deleteLater()
def action_1(self):
print('Menu 1 0')
def action_2(self):
print('Menu 1 1')
if __name__ == '__main__':
app=QApplication(sys.argv)
new=MyWindow()
new.show()
app.exec_()

Categories