I am dealing with the following problem, while I am having multiple windows open, i would like to build a function linked to a button to bring to the front the Main window.
Thank you in advance.
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QLabel)
class Window2(QMainWindow): # <===
def __init__(self):
super().__init__()
self.setWindowTitle("Window 2")
self.pushButton = QPushButton("Back to window1", self)
self.pushButton.clicked.connect(self.window1)
def window1(self): # <===
pass;
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "First Window"
self.top = 100
self.left = 100
self.width = 680
self.height = 500
self.pushButton = QPushButton("Go to window 2 ", self)
self.pushButton.move(275, 200)
self.label = QLabel("window 1", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.pushButton.clicked.connect(self.window2) # <===
def window2(self): # <===
self.w = Window2()
self.w.show()
def main():
app = QApplication(sys.argv)
window = Window()
window.show()
#app.exec_()
exit(app.exec_())
if __name__=='__main__':
main()
Regards
I am expecting a function to call back the widget "Window"
CodePudding user response:
You could emit a signal from your second window that your fist window listens for, and calls .raise_()
when triggered.
Update: Added a call to activateWindow
in the first windows callback. thanks @musicmante
For example:
import sys
from PyQt5 import QtGui
from PyQt5.QtCore import pyqtSignal # import signal
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QLabel)
class Window2(QMainWindow):
unfocus = pyqtSignal() # create signal
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setWindowTitle("Window 2")
self.pushButton = QPushButton("Back to window1", self)
# button press emits signal
self.pushButton.clicked.connect(self.unfocus.emit)
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "First Window"
self.top = 100
self.left = 100
self.width = 680
self.height = 500
self.pushButton = QPushButton("Go to window 2 ", self)
self.pushButton.move(275, 200)
self.label = QLabel("window 1", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.pushButton.clicked.connect(self.window2) # <===
def window2(self): # <===
self.w = Window2()
self.w.unfocus.connect(self.bring_to_top) # listen for signal and raise_ to top focus
self.w.show()
def bring_to_top(self):
self.activateWindow()
self.raise_()
def main():
app = QApplication(sys.argv)
window = Window()
window.show()
#app.exec_()
exit(app.exec_())
if __name__=='__main__':
main()