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.
Related
I have a PySide2 GUI that accepts a number from the user on page one then does some calculations and displays the results on page two. Each page is a QWidget within a QStackedWidget. There is a pushbutton on page two, the results page, that sends the user back to page one to enter a new number.
My problem is that when I enter a new number the results never change from the first number. I use print statements to confirm that the labels on the results page are updating but the display stays the same.
# importing the module
import os
import sys
from PySide2 import QtWidgets
import PySide2.QtUiTools as QtUiTools
class IncomeScreen(QtWidgets.QMainWindow):
def __init__(self):
super(IncomeScreen, self).__init__()
# Load the IncomeScreen ui
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "main.ui")
self.main = loader.load(path, self)
# Connect the signals with custom slots
self.main.calculate_pushButton.clicked.connect(self.calculate)
def calculate(self):
init_amount = self.main.income_lineEdit.text()
IncomeScreen.init_amount = float(init_amount)
# Create an instance of DistributionScreen class
self.distribution = DistributionScreen()
# Add DistributionScreen to the stacked widget
widget.addWidget(self.distribution)
# Change index to show DownloadPage
widget.setCurrentIndex(widget.currentIndex()+1)
class DistributionScreen(QtWidgets.QMainWindow):
def __init__(self):
super(DistributionScreen, self).__init__()
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "dialog.ui")
self.dialog = loader.load(path, self)
# Set initial amount to label
self.dialog.initialAmount_label.setText(str(IncomeScreen.init_amount))
print("Initial Amount = {:0.2f}".format(IncomeScreen.init_amount))
# 10 Percent
ten = IncomeScreen.init_amount * 0.1
print("10% = {:0.2f}".format(ten))
self.dialog.label_10percent.setText("{:0.2f}".format(ten))
print(self.dialog.label_10percent.text())
# 20 percent
twenty = IncomeScreen.init_amount * 0.2
print("20% = {:0.2f}".format(twenty))
self.dialog.label_20percent.setText("{:0.2f}".format(twenty))
print(self.dialog.label_20percent.text())
# Update widget
self.dialog.update()
# Connect the signals with custom slots
self.dialog.reset_pushButton.clicked.connect(self.reset)
def reset(self):
print("reset")
# Change index to show IncomeScreen
widget.setCurrentIndex(widget.currentIndex()-1)
# main
# if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
income = IncomeScreen()
widget = QtWidgets.QStackedWidget()
widget.addWidget(income)
widget.show()
try:
sys.exit(app.exec_())
except:
print("Exiting")
Also I'm using Python 3.7.4
EDIT: You can download the ui files here
There are various problems with your code, but the most important one is that every time calculate is called, a new DistributionScreen is added to the stacked widget, but widget.setCurrentIndex(widget.currentIndex()+1) will always go to the second index of the stacked widget (which is the first instance you created).
A possible simple workaround could be to use the index of the widget returned by addWidget or use setCurrentWidget:
def calculate(self):
init_amount = self.main.income_lineEdit.text()
IncomeScreen.init_amount = float(init_amount)
self.distribution = DistributionScreen()
index = widget.addWidget(self.distribution)
widget.setCurrentIndex(index)
# alternatively:
widget.setCurrentWidget(self.distribution)
Unfortunately, while this would make your code work, it's not a valid solution, as there are other important issues that would create other problems sooner or later:
a stacked widget works like a tab widget: it's intended to allow reusability of the widgets; you should not constantly create a new instance every time, but possibly use the existing one;
you should not set nor use a class attribute for a variable that depends on an instance (as you did with IncomeScreen.init_amount);
you're adding QMainWindows to a stacked widget, which is discouraged, as a main window should be used as a top level window (it has features that rely on that aspect); note that even QDialog is not a valid candidate, and you should opt for a basic QWidget or a container like QFrame or QGroupBox;
you're using QUiLoader to load the widget as a child of the main window, but without adding it to a layout (or setting as central widget), and this will make it unable to resize itself whenever the top level window is resized: if the main window becomes too small, some of the contents won't be visible, if it's too big there will be a lot of unused space;
you're trying to access a global variable (widget) from an instance, while it's not guaranteed that the variable would be valid; in any case, it should not be the instance to create new widgets and set the index of the stacked widget, but the stacked widget itself (or any of its ancestors);
the last try/except block is very dangerous, as it prevents you to capture exceptions (since it's a generic except:) or know what was wrong with your program if it crashes;
This is a possible revision of your code (untested, as you didn't provide the ui files).
import os
import sys
from PySide2 import QtWidgets, QtCore
import PySide2.QtUiTools as QtUiTools
class IncomeScreen(QtWidgets.QWidget):
# a custom signal to notify that we want to show the distribution page
# with the provided value
goToDistribution = QtCore.Signal(float)
def __init__(self):
super(IncomeScreen, self).__init__()
# Load the IncomeScreen ui
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "main.ui")
self.main = loader.load(path, self)
# a proper layout that manages the contents loaded with QUiLoader
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.main)
# Connect the signals with custom slots
self.main.calculate_pushButton.clicked.connect(self.calculate)
def calculate(self):
init_amount = self.main.income_lineEdit.text()
self.goToDistribution.emit(float(init_amount))
class DistributionScreen(QtWidgets.QWidget):
reset = QtCore.Signal()
def __init__(self):
super(DistributionScreen, self).__init__()
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "dialog.ui")
self.dialog = loader.load(path, self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.dialog)
self.dialog.reset_pushButton.clicked.connect(self.reset)
def setIncome(self, value):
# Set initial amount to label
self.dialog.initialAmount_label.setText(str(value))
print("Initial Amount = {:0.2f}".format(value))
# 10 Percent
ten = value * 0.1
print("10% = {:0.2f}".format(ten))
self.dialog.label_10percent.setText("{:0.2f}".format(ten))
print(self.dialog.label_10percent.text())
# 20 percent
twenty = value * 0.2
print("20% = {:0.2f}".format(twenty))
self.dialog.label_20percent.setText("{:0.2f}".format(twenty))
print(self.dialog.label_20percent.text())
class MainWidget(QtWidgets.QStackedWidget):
def __init__(self):
super(MainWidget, self).__init__()
# create *both* the pages here
self.income = IncomeScreen()
self.addWidget(self.income)
self.distribution = DistributionScreen()
self.addWidget(self.distribution)
self.income.goToDistribution.connect(self.goToDistribution)
self.distribution.reset.connect(self.reset)
def goToDistribution(self, value):
# we received the notification signal, then we set the value and
# show the related page by switching to it
self.distribution.setIncome(value)
self.setCurrentWidget(self.distribution)
def reset(self):
self.setCurrentWidget(self.income)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWidget = MainWidget()
mainWidget.show()
sys.exit(app.exec_())
Note that:
if you want a numeric control, you should use QSpinBox or QDoubleSpinBox (for floating point numbers), or set a QIntValidator or QDoubleValidator, otherwise if the user enters a non numeric value your program will crash (due to the usage of float() done without previously checking if the string is actually a valid number);
while QUiLoader is useful, it has the drawback of always creating a widget, so you can never override its methods; the only solution to this is to use files generated by pyside-uic and use the multiple inheritance method, or switch to PyQt and use its uic.loadUi which instead allows setting up the UI on the current widget;
most of the problems in your code are due to some tutorials that have been shared lately (some of them on youtube): unfortunately, those tutorials suggest a lot of terrible things that should not be done, both for PyQt and Python; I strongly suggest you to look for other resources and, most importantly, always study the documentation.
I have a PySide2 GUI that accepts a number from the user on page one then does some calculations and displays the results on page two. Each page is a QWidget within a QStackedWidget. There is a pushbutton on page two, the results page, that sends the user back to page one to enter a new number.
My problem is that when I enter a new number the results never change from the first number. I use print statements to confirm that the labels on the results page are updating but the display stays the same.
# importing the module
import os
import sys
from PySide2 import QtWidgets
import PySide2.QtUiTools as QtUiTools
class IncomeScreen(QtWidgets.QMainWindow):
def __init__(self):
super(IncomeScreen, self).__init__()
# Load the IncomeScreen ui
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "main.ui")
self.main = loader.load(path, self)
# Connect the signals with custom slots
self.main.calculate_pushButton.clicked.connect(self.calculate)
def calculate(self):
init_amount = self.main.income_lineEdit.text()
IncomeScreen.init_amount = float(init_amount)
# Create an instance of DistributionScreen class
self.distribution = DistributionScreen()
# Add DistributionScreen to the stacked widget
widget.addWidget(self.distribution)
# Change index to show DownloadPage
widget.setCurrentIndex(widget.currentIndex()+1)
class DistributionScreen(QtWidgets.QMainWindow):
def __init__(self):
super(DistributionScreen, self).__init__()
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "dialog.ui")
self.dialog = loader.load(path, self)
# Set initial amount to label
self.dialog.initialAmount_label.setText(str(IncomeScreen.init_amount))
print("Initial Amount = {:0.2f}".format(IncomeScreen.init_amount))
# 10 Percent
ten = IncomeScreen.init_amount * 0.1
print("10% = {:0.2f}".format(ten))
self.dialog.label_10percent.setText("{:0.2f}".format(ten))
print(self.dialog.label_10percent.text())
# 20 percent
twenty = IncomeScreen.init_amount * 0.2
print("20% = {:0.2f}".format(twenty))
self.dialog.label_20percent.setText("{:0.2f}".format(twenty))
print(self.dialog.label_20percent.text())
# Update widget
self.dialog.update()
# Connect the signals with custom slots
self.dialog.reset_pushButton.clicked.connect(self.reset)
def reset(self):
print("reset")
# Change index to show IncomeScreen
widget.setCurrentIndex(widget.currentIndex()-1)
# main
# if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
income = IncomeScreen()
widget = QtWidgets.QStackedWidget()
widget.addWidget(income)
widget.show()
try:
sys.exit(app.exec_())
except:
print("Exiting")
Also I'm using Python 3.7.4
EDIT: You can download the ui files here
There are various problems with your code, but the most important one is that every time calculate is called, a new DistributionScreen is added to the stacked widget, but widget.setCurrentIndex(widget.currentIndex()+1) will always go to the second index of the stacked widget (which is the first instance you created).
A possible simple workaround could be to use the index of the widget returned by addWidget or use setCurrentWidget:
def calculate(self):
init_amount = self.main.income_lineEdit.text()
IncomeScreen.init_amount = float(init_amount)
self.distribution = DistributionScreen()
index = widget.addWidget(self.distribution)
widget.setCurrentIndex(index)
# alternatively:
widget.setCurrentWidget(self.distribution)
Unfortunately, while this would make your code work, it's not a valid solution, as there are other important issues that would create other problems sooner or later:
a stacked widget works like a tab widget: it's intended to allow reusability of the widgets; you should not constantly create a new instance every time, but possibly use the existing one;
you should not set nor use a class attribute for a variable that depends on an instance (as you did with IncomeScreen.init_amount);
you're adding QMainWindows to a stacked widget, which is discouraged, as a main window should be used as a top level window (it has features that rely on that aspect); note that even QDialog is not a valid candidate, and you should opt for a basic QWidget or a container like QFrame or QGroupBox;
you're using QUiLoader to load the widget as a child of the main window, but without adding it to a layout (or setting as central widget), and this will make it unable to resize itself whenever the top level window is resized: if the main window becomes too small, some of the contents won't be visible, if it's too big there will be a lot of unused space;
you're trying to access a global variable (widget) from an instance, while it's not guaranteed that the variable would be valid; in any case, it should not be the instance to create new widgets and set the index of the stacked widget, but the stacked widget itself (or any of its ancestors);
the last try/except block is very dangerous, as it prevents you to capture exceptions (since it's a generic except:) or know what was wrong with your program if it crashes;
This is a possible revision of your code (untested, as you didn't provide the ui files).
import os
import sys
from PySide2 import QtWidgets, QtCore
import PySide2.QtUiTools as QtUiTools
class IncomeScreen(QtWidgets.QWidget):
# a custom signal to notify that we want to show the distribution page
# with the provided value
goToDistribution = QtCore.Signal(float)
def __init__(self):
super(IncomeScreen, self).__init__()
# Load the IncomeScreen ui
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "main.ui")
self.main = loader.load(path, self)
# a proper layout that manages the contents loaded with QUiLoader
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.main)
# Connect the signals with custom slots
self.main.calculate_pushButton.clicked.connect(self.calculate)
def calculate(self):
init_amount = self.main.income_lineEdit.text()
self.goToDistribution.emit(float(init_amount))
class DistributionScreen(QtWidgets.QWidget):
reset = QtCore.Signal()
def __init__(self):
super(DistributionScreen, self).__init__()
loader = QtUiTools.QUiLoader()
path = os.path.join(os.path.dirname(__file__), "dialog.ui")
self.dialog = loader.load(path, self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.dialog)
self.dialog.reset_pushButton.clicked.connect(self.reset)
def setIncome(self, value):
# Set initial amount to label
self.dialog.initialAmount_label.setText(str(value))
print("Initial Amount = {:0.2f}".format(value))
# 10 Percent
ten = value * 0.1
print("10% = {:0.2f}".format(ten))
self.dialog.label_10percent.setText("{:0.2f}".format(ten))
print(self.dialog.label_10percent.text())
# 20 percent
twenty = value * 0.2
print("20% = {:0.2f}".format(twenty))
self.dialog.label_20percent.setText("{:0.2f}".format(twenty))
print(self.dialog.label_20percent.text())
class MainWidget(QtWidgets.QStackedWidget):
def __init__(self):
super(MainWidget, self).__init__()
# create *both* the pages here
self.income = IncomeScreen()
self.addWidget(self.income)
self.distribution = DistributionScreen()
self.addWidget(self.distribution)
self.income.goToDistribution.connect(self.goToDistribution)
self.distribution.reset.connect(self.reset)
def goToDistribution(self, value):
# we received the notification signal, then we set the value and
# show the related page by switching to it
self.distribution.setIncome(value)
self.setCurrentWidget(self.distribution)
def reset(self):
self.setCurrentWidget(self.income)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWidget = MainWidget()
mainWidget.show()
sys.exit(app.exec_())
Note that:
if you want a numeric control, you should use QSpinBox or QDoubleSpinBox (for floating point numbers), or set a QIntValidator or QDoubleValidator, otherwise if the user enters a non numeric value your program will crash (due to the usage of float() done without previously checking if the string is actually a valid number);
while QUiLoader is useful, it has the drawback of always creating a widget, so you can never override its methods; the only solution to this is to use files generated by pyside-uic and use the multiple inheritance method, or switch to PyQt and use its uic.loadUi which instead allows setting up the UI on the current widget;
most of the problems in your code are due to some tutorials that have been shared lately (some of them on youtube): unfortunately, those tutorials suggest a lot of terrible things that should not be done, both for PyQt and Python; I strongly suggest you to look for other resources and, most importantly, always study the documentation.
It's my code. How to store the lastly clicked/checked button as default in the next opening of the programme? For example: If we run the programme and click the 3rd button and close the entire programme. Whenever I reopen/re-run the programme, the lastly clicked button is checked by default ( ie. third button is checked by default)
import sys
from PyQt5 import QtWidgets
class RadioButton(QtWidgets.QWidget):
def __init__(self):
super(). __init__()
self.setWindowTitle("Radio Button")
self.rbtn1 = QtWidgets.QRadioButton("Button1")
self.rbtn1.clicked.connect(self.getvalue)
self.rbtn2 = QtWidgets.QRadioButton("Button2")
self.rbtn2.clicked.connect(self.getvalue)
self.rbtn3 = QtWidgets.QRadioButton("Button3")
self.rbtn3.clicked.connect(self.getvalue)
self.rbtn4 = QtWidgets.QRadioButton("Button4")
self.rbtn4.clicked.connect(self.getvalue)
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.rbtn1)
vbox.addWidget(self.rbtn2)
vbox.addWidget(self.rbtn3)
vbox.addWidget(self.rbtn4)
self.setLayout(vbox)
def getvalue(self):
if self.rbtn1.isChecked():
self.rbtn1.setChecked(True)
print("Radio button 1 is checked")
elif self.rbtn2.isChecked():
self.rbtn2.setChecked(True)
print("Radio button 2 is checked")
elif self.rbtn3.isChecked():
self.rbtn3.setChecked(True)
print("Radio button 3 is checked")
elif self.rbtn4.isChecked():
self.rbtn4.setChecked(True)
print("Radio button 4 is checked")
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
win = RadioButton()
win.show()
sys.exit(app.exec_())
You can use QSettings to save and restore data. Note that values are serialized as QVariants, so you cannot, for instance, save a custom python subclass instance.
In order to properly use QSettings you must set both the Qt application name and organization name (otherwise data won't be stored anywhere).
It is possible to save settings in other ways, but for general usage it's better to use the default behavior.
Note that, since values are stored as strings, Qt can only try to guess the actual type, so it's always better to specify the type when using value() (see the case below).
Then, while by default Qt is able to automatically group radio buttons and make them exclusive (see the autoExclusive property of QAbstractButton, which is set to True for QRadioButtons), for this kind of situations it's better to rely on a QButtonGroup, which not only allows better control on the buttons, but also allows identifying buttons member of the group by using unique IDs they were assigned to.
Finally, it's just a matter of connecting the appropriate signal of the button group to the function that saves the currently checked button.
from PyQt5 import QtWidgets, QtCore
class RadioButton(QtWidgets.QWidget):
def __init__(self):
super(). __init__()
self.setWindowTitle("Radio Button")
self.rbtn1 = QtWidgets.QRadioButton("Button1")
self.rbtn2 = QtWidgets.QRadioButton("Button2")
self.rbtn3 = QtWidgets.QRadioButton("Button3")
self.rbtn4 = QtWidgets.QRadioButton("Button4")
buttons = self.rbtn1, self.rbtn2, self.rbtn3, self.rbtn4
vbox = QtWidgets.QVBoxLayout(self)
self.optionGroup = QtWidgets.QButtonGroup()
for i, button in enumerate(buttons):
vbox.addWidget(button)
self.optionGroup.addButton(button, i)
# for Qt>=5.15:
# self.optionGroup.idToggled.connect(self.getvalue)
# otherwise:
self.optionGroup.buttonToggled[int, bool].connect(self.getvalue)
self.settings = QtCore.QSettings()
# read the value if it exists, otherwise use a default; note that
# the type MUST be specified, otherwise numbers would be read as
# strings, raising an exception and crashing the program in this case
default = self.settings.value('MyOption', 2, type=int)
self.optionGroup.button(default).setChecked(True)
def getvalue(self, id, checked):
if checked:
button = self.optionGroup.button(id)
print("{} is checked".format(button.text()))
self.settings.setValue('MyOption', id)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setOrganizationName('MyOrganization')
app.setApplicationName('MyApplication')
win = RadioButton()
win.show()
sys.exit(app.exec_())
I strongly recommend you to carefully study the whole documentation about all the classes specified above.
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.
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/