Pyqt5 - how to go back to hided Main Window from Secondary Window? - python

If I click Back from the second window, the program will just exit. How do I go back to mainwindow in this case? I assume I will need some more code in that clickMethodBack function.
import os
import PyQt5
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QPushButton
import time
from PyQt5.QtCore import QSize
class GUI_Window():
def __init__(self):
self.main_window()
return
def main_window(self):
app = PyQt5.QtWidgets.QApplication(sys.argv)
self.MainWindow = MainWindow_()
self.MainWindow.show()
app.exec_()
return
class MainWindow_(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.TestAButton = QPushButton("TestA", self)
self.TestAButton.clicked.connect(self.TestA_clickMethod)
self.TestAButton.move(20, 0)
self.CloseButton = QPushButton("Close", self)
self.CloseButton.clicked.connect(self.Close_clickMethod)
self.CloseButton.move(20, 40)
self.TestingA = TestA_MainWindow()
def TestA_clickMethod(self):
self.TestAButton.setEnabled(False)
time.sleep(0.2)
self.TestingA.show()
self.hide()
try:
if self.TestingA.back == True:
self.show()
except:
None
def Close_clickMethod(self):
self.Test_Choice = 'Exit'
self.close()
class TestA_MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setMinimumSize(QSize(980,700))
self.setWindowTitle("TestA")
self.Back_Button = False
self.closeButton = QPushButton("Close", self)
self.closeButton.clicked.connect(self.clickMethodClose)
self.returnButton = QPushButton("Back", self)
self.returnButton.clicked.connect(self.clickMethodBack)
self.returnButton.move(0,30)
def clickMethodClose(self):
self.Back_Button = False
self.close()
def clickMethodBack(self):
self.returnButton.setEnabled(False)
time.sleep(0.5)
self.back = True
self.close()
# Run if Script
if __name__ == "__main__":
main = GUI_Window() # Initialize GUI

Your code has two very important issues.
you're using a blocking function, time.sleep; Qt, as almost any UI toolkit, is event driven, which means that it has to be able to constantly receive and handle events (coming from the system or after user interaction): when something blocks the event queue, it completely freezes the whole program until that block releases control;
you're checking for the variable too soon: even assuming the sleep would work, you cannot know if the window is closed after that sleep timer has ended;
The solution is to use signals and slots. Since you need to know when the second window has been closed using the "back" button, create a custom signal for the second window that will be emitted whenever the function that is called by the button is closed.
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
central = QtWidgets.QWidget()
layout = QtWidgets.QHBoxLayout(central)
self.testButton = QtWidgets.QPushButton('Test A')
self.closeButton = QtWidgets.QPushButton('Close')
layout.addWidget(self.testButton)
layout.addWidget(self.closeButton)
self.setCentralWidget(central)
self.testButton.clicked.connect(self.launchWindow)
self.closeButton.clicked.connect(self.close)
def launchWindow(self):
self.test = TestA_MainWindow()
self.test.backSignal.connect(self.show)
self.hide()
self.test.show()
class TestA_MainWindow(QtWidgets.QWidget):
backSignal = QtCore.pyqtSignal()
def __init__(self):
super().__init__()
layout = QtWidgets.QHBoxLayout(self)
self.closeButton = QtWidgets.QPushButton('Close')
self.backButton = QtWidgets.QPushButton('Back')
layout.addWidget(self.closeButton)
layout.addWidget(self.backButton)
self.closeButton.clicked.connect(self.close)
self.backButton.clicked.connect(self.goBack)
def goBack(self):
self.close()
self.backSignal.emit()
def GUI_Window():
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
if __name__ == '__main__':
GUI_Window()
Notes:
I removed the GUI_Window class and made a function, as using a class for that is not really useful;
you should always prefer layout managers instead of setting manual geometries;
widgets should not be added to a QMainWindow as direct children, and a central widget should always be used (see the creation and use of central in the example); read more about it in the documentation;
only classes and constants should be capitalized, while variables, attributes and functions should always have names starting with a lowercase letter;

Related

PyQt5 - Detecting When Other Window Closes

I’m using PyQt5 and I need to have my main window detect when a different window closes. I read here Emit a signal from another class to main class that creating a signal class to serve as an intermediary should work. However I haven’t gotten my example to work.
In my example, clicking the button opens a QWidget window. When the QWidget is closed, the main window is supposed to change from a blue background to a red background. However, the main window remains blue using the script below.
What am I doing wrong?
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QObject, pyqtSignal
import os, sys
class MySignal(QObject):
signal = pyqtSignal()
class MyMainWindow(QMainWindow):
def __init__(self):
super().__init__()
#Make mainwindow
self.setGeometry(100,100,300,200)
self.setStyleSheet('background-color: blue')
# Make widget and button objects and set connection
self.widget = MyWidget()
self.btn = QPushButton(self)
self.btn.setText('Click')
self.btn.move(175, 150)
self.btn.setStyleSheet('background-color: white')
self.btn.clicked.connect(self.widget.showWidget)
# Make signal object and set connection
self.mySignal = MySignal()
self.mySignal.signal.connect(self.changeToRed)
# Let's start
self.show()
def changeToRed(self):
self.setStyleSheet('background-color: red')
def closeEvent(self, event):
os._exit(0)
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(500, 100, 200, 200)
self.sig = MySignal()
def showWidget(self):
self.show()
def closeEvent(self, event):
self.sig.signal.emit()
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyMainWindow()
app.exec()```
The reason your code fails is that the connected signal object in MyMainWindow is not the same as the one you create in MyWidget, so the signal is never emitted. Here is a modified solution using signals in the normal way:
from PyQt5.QtWidgets import QPushButton, QMainWindow, QWidget, QApplication
from PyQt5.QtCore import QObject, pyqtSignal
import os, sys
class MyMainWindow(QMainWindow):
def __init__(self):
super().__init__()
#Make mainwindow
self.setGeometry(100,100,300,200)
self.setStyleSheet('background-color: blue')
# Make widget and button objects and set connection
self.widget = MyWidget()
self.btn = QPushButton(self)
self.btn.setText('Click')
self.btn.move(175, 150)
self.btn.setStyleSheet('background-color: white')
self.btn.clicked.connect(self.widget.showWidget)
self.widget.sig.connect(self.changeToRed)
# Let's start
self.show()
def changeToRed(self):
self.setStyleSheet('background-color: red')
class MyWidget(QWidget):
sig = pyqtSignal()
def __init__(self):
super().__init__()
self.setGeometry(500, 100, 200, 200)
def showWidget(self):
self.show()
def closeEvent(self, event):
self.sig.emit()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyMainWindow()
app.exec()
All you need is to add the connection between the close event and the function that turn your main screen red:
self.widget.closeEvent = self.changeToRed
this line should be in your main Window class
change your changeToRed function so it will except the event too:
def changeToRed(self, e):

Python program subclasses a PyQt5 Window cant setwindow.title in Function

I have a sample Python program that sub classes a PyQt5 window. I am teaching myself and still a little new PyQt5 and python Classes.
The program does what I want to do I ran into an error that I don't understand how to fix. To start this program functions as is, I am currently learning how to run Threads. I imported and sub classed the PyQt5 window. In the __init__ section of the subclass I can set the window title and it works fine.
If I move the statement to a function "def initUI(self):" I am unable to set the window title, mind you I have tried various versions of the statement and nothing works. It's the first line of the def and I have it commented out.
My questions are:
Is this property setable in a def.
If it io what is the proper format of the statement.
from PyQt5.QtCore import pyqtSlot, pyqtSignal
from PyQt5 import QtCore, QtGui, QtWidgets
from Threads import Ui_MainWindow
import sys, time
from time import sleep
class MainWindow_EXEC():
def __init__(self): # This section has to be laid out this way
app = QtWidgets.QApplication(sys.argv)
win = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(win)
self.initUI() # Inits that need to happen before start up
win.setWindowTitle("This is the Title!") # Works fine
win.resize(800,600)
win.show()
sys.exit(app.exec_())
def initUI(self): # Button assignments
#self.ui.setWindowTitle("This is the Title!") # AttributeError: 'Ui_MainWindow' object has no attribute 'setWindowTitle'
self.ui.btn_Start.clicked.connect(self.start_progressbar)
self.ui.btn_Stop.clicked.connect(self.stop_progressbar)
self.ui.btn_Reset.clicked.connect(self.reset_progressbar)
self.progress_value = 0
self.stop_progress = False
def progressbar_counter(self, start_value=0):
# have to use member: self.run_thread NOT local var: run_thread
self.run_thread = RunThread(parent=None, counter_start=start_value)
self.run_thread.start()
self.run_thread.counter_value.connect(self.get_thread_value)
def get_thread_value(self, counter): #This updates the progress bar
print(counter)
if not self.stop_progress:
self.ui.progressBar.setValue(counter)
def start_progressbar(self): # This is the button that starts the progress bar
self.stop_progress = False # This is a switch
self.progress_value = self.ui.progressBar.value() # Updating the progress bar
self.progressbar_counter(self.progress_value)
def stop_progressbar(self): # This is a button to stop the progress bar
self.stop_progress = True
self.run_thread.stop()
def reset_progressbar(self): # This is a button to reset the progress bar
self.stop_progressbar()
self.progress_value = 0
self.stop_progress = False
self.ui.progressBar.reset()
class RunThread(QtCore.QThread):
counter_value = QtCore.pyqtSignal(int) # define new Signal
def __init__(self, parent=None, counter_start=0):
super(RunThread, self).__init__(parent)
self.counter = counter_start
self.isRunning = True
def run(self):
while self.counter < 100 and self.isRunning == True:
sleep(0.1)
self.counter += 1
print(self.counter)
self.counter_value.emit(self.counter) # emit new Signal with value
def stop(self):
self.isRunning = False
print('stopping thread...')
self.terminate()
if __name__ == "__main__":
MainWindow_EXEC()
The objective of the following classes must be distinguished:
QMainWindow is a widget that has the setWindowTitle method.
Ui_MainWindow is not a widget but a class that is used to fill a widget so it does not have the setWindowTitle method.
The solution is to make win a class member and then use that object to modify the title:
class MainWindow_EXEC():
def __init__(self): # This section has to be laid out this way
app = QtWidgets.QApplication(sys.argv)
self.win = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.win)
self.initUI()
self.win.setWindowTitle("This is the Title!")
self.win.resize(800,600)
self.win.show()
sys.exit(app.exec_())
def initUI(self): # Button assignments
self.win.setWindowTitle("This is the Title!")
self.ui.btn_Start.clicked.connect(self.start_progressbar)
# ...

How do I get a signal from a QWiget to change get object?

Hello I have a QWidget and If I click on it, I want to get the object (the QWidget Element I clicked on) is there anyway to do that?
I already found some code but I only get the MouseClickEvent from
self.widget_34.mouseReleaseEvent = lambda event: self.myfunction(event)
Although the solution offered by #Cin is interesting, it has a serious problem: it cancels the mousePressEvent of the widget, so the widget loses the behavior it could have when the widget is pressed, for example the button no longer emits the clicked signal, other widget also They will have the same problem.
A less intrusive solution is to use eventFilter:
import sys
import weakref
from PyQt5 import QtCore, QtWidgets
class ClickListener(QtCore.QObject):
clicked = QtCore.pyqtSignal(QtWidgets.QWidget)
def addWidget(self, widget, other_widget=None):
if not hasattr(self, "_widgets"):
self._widgets = {}
widget.installEventFilter(self)
self._widgets[widget] = widget if other_widget is None else other_widget
weakref.ref(widget, self.removeWidget)
def eventFilter(self, obj, event):
if (
obj in self._widgets
and event.type() == QtCore.QEvent.MouseButtonPress
):
self.clicked.emit(self._widgets[obj])
return super(ClickListener, self).eventFilter(obj, event)
def removeWidget(self, widget):
if hasattr(self, "_widgets"):
if widget in self._widgets:
del self._widgets[widget]
class App(QtWidgets.QWidget):
def __init__(self):
super().__init__()
button = QtWidgets.QPushButton("Press Me")
label = QtWidgets.QLabel("Stack Overflow")
spinBox = QtWidgets.QSpinBox()
te = QtWidgets.QTextEdit()
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(button)
lay.addWidget(label)
lay.addWidget(spinBox)
lay.addWidget(te)
listener = ClickListener(self)
listener.clicked.connect(self.onClicked)
listener.addWidget(button)
listener.addWidget(label)
listener.addWidget(spinBox.lineEdit(), spinBox)
listener.addWidget(te.viewport(), te)
def onClicked(self, obj):
print("Clicked, from", obj)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
I am not sure this will be a proper solution or not but I think, you can use the partial method of functools module. A collable object can be treated as a function for the purposes of this module. Here you can see my example,
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel
import functools
class App(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(200,200,200,200)
self.button = QPushButton('Button', self)
self.button.move(50,50)
self.label = QLabel(self)
self.label.setText("Label")
self.label.move(100,100)
self.items = [self.button, self.label]
for i in self.items:
i.mousePressEvent = functools.partial(self.getClickedItem, source_object=i)
self.show()
def getClickedItem(self, event, source_object=None):
print("Clicked, from", source_object)
#item text
#print(source_object.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

How can I stop printing numbers clicking on a pushbutton

I want to start printing numbers in a GUI in pyqt4 but when I pressed the start button it freezes and I have to close de window, I want start the psocess clicking on a button and stoped with another button, here I let my code
This is the part where I tried to start and stop the process
class LecturaFrecuencia(QMainWindow):
"""docstring for LecturaFrecuencia"""
def __init__(self, parent):
super(LecturaFrecuencia, self).__init__(parent)
uic.loadUi('frecuencia.ui', self)
global START
self.button_volver.clicked.connect(self.regresar)
self.button_terminar.clicked.connect(self.terminar_monitoreo)
self.button_guardar.clicked.connect(self.guardar)
self.button_iniciar.clicked.connect(self.iniciarLectura)
def iniciarLectura(self):
START = 1
while START :
pqrst= random.randint(55,101)
time.sleep(1.0)
print(str(pqrst))
self.pqrst.setText(str(pqrst))
if self.button_terminar.isChecked():
START = 0
else:
pass
Never use time.sleep() in the GUI thread since it will freeze it. If you want to do periodic tasks use a QTimer:
import random
from PyQt4 import QtCore, QtGui, uic
class LecturaFrecuencia(QtGui.QMainWindow):
"""docstring for LecturaFrecuencia"""
def __init__(self, parent=None):
super(LecturaFrecuencia, self).__init__(parent)
uic.loadUi('frecuencia.ui', self)
timer = QtCore.QTimer(
self,
interval=1000,
timeout=self.processing
)
self.button_iniciar.clicked.connect(timer.start)
self.button_terminar.clicked.connect(timer.stop)
#QtCore.pyqtSlot()
def processing(self):
pqrst = random.randint(55,101)
self.pqrst.setText("{}".format(pqrst))
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = LecturaFrecuencia()
w.show()
sys.exit(app.exec_())

PyQt : Prevent a window to be opened several times

I made the simple code below as example. It justs open a new window clicking on a button. I don't find a way to prevent this widget to be re-opened if it is already on the screen. I would like to open a QDialog warning if the window already exists and mainly to have the closeEvent method sending a signal to Mainwidget saying that the new window has been closed. This would allow to open the newWidget again.
import sys
from PyQt4 import QtCore, QtGui
class NewWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(NewWidget,self).__init__(parent)
self.lineEdit = QtGui.QLineEdit('new window',self)
self.resize(200,50)
self.show()
def closeEvent(self,ev):
self.Exit = QtGui.QMessageBox.question(self,
"Confirm Exit...",
"Are you sure you want to exit ?",
QtGui.QMessageBox.Yes| QtGui.QMessageBox.No)
ev.ignore()
if self.Exit == QtGui.QMessageBox.Yes:
ev.accept()
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MainWidget,self).__init__(parent)
self.button = QtGui.QPushButton("button", self)
self.button.clicked.connect(self.open_new)
def open_new(self):
self.new = NewWidget()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
main = MainWidget()
main.resize(200,50)
main.move(app.desktop().screen().rect().center() - main.rect().center())
main.show()
sys.exit(app.exec_())
I think a better solution is to avoid creating a new window every time you click the button.
One way to do this would be to change the subwindow to a QDialog:
class NewWidget(QtGui.QDialog):
...
and move the resize/show lines into the open_new method:
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None):
...
self._subwindow = None
def open_new(self):
if self._subwindow is None:
self._subwindow = NewWidget(self)
self._subwindow.resize(200, 50)
# move it next to the main window
pos = self.frameGeometry().topLeft()
self._subwindow.move(pos.x() - 250, pos.y())
self._subwindow.show()
self._subwindow.activateWindow()
So now there is only ever one subwindow, which just gets re-activated whenever the button is clicked.
Great. The final solution of my problem looks like this :
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None):
...
self._subwindow = QtGui.Qdialog()
def open_new(self):
if self.subwindow.isVisible() is False:
self._subwindow = NewWidget(self)
self._subwindow.resize(200, 50)
# move it next to the main window
pos = self.frameGeometry().topLeft()
self._subwindow.move(pos.x() - 250, pos.y())
self._subwindow.show()
self._subwindow.activateWindow()

Categories

Resources