Need Switching between 2 Mainwindows in Pyqt5 [duplicate] - python

This question already has answers here:
How to switch between two PyQt5 MainWindow widgets
(2 answers)
Closed 3 years ago.
I have created 2 separate MainWindow(in 2 different programs). Now I need to switch between these 2 windows. Example: When a button in MainWindow1 is clicked , MainWindow2 should be opened and MainWindow1 should be closed and vice versa. Please help!

Try it:
import sys
from PyQt5 import Qt
class MainWindow1(Qt.QMainWindow):
def __init__(self):
Qt.QMainWindow.__init__(self)
self.mainWindow1()
def mainWindow1(self):
self.setFixedSize(300, 300)
self.setStyleSheet('background-color : rgb(255,255,255);')
self.setWindowTitle('MainWindow1')
self.pushButton = Qt.QPushButton(self)
self.pushButton.setStyleSheet('background-color: rgb(255,0,0); color: #fff')
self.pushButton.setText('Click me!')
self.pushButton.clicked.connect(self.A)
def A(self):
self.cams = MainWindow2()
self.cams.show()
self.close()
class MainWindow2(Qt.QMainWindow):
def __init__(self):
Qt.QMainWindow.__init__(self)
self.setFixedSize(500, 500)
self.setStyleSheet('background-color : rgb(255,0,0);')
self.setWindowTitle('MainWindow2')
self.pushButton = Qt.QPushButton(self)
self.pushButton.setStyleSheet('background-color: rgb(0,0,255); color: #fff')
self.pushButton.setText('Click me!')
self.pushButton.clicked.connect(self.B)
def B(self):
self.cams = MainWindow1()
self.cams.show()
self.close()
if __name__ == '__main__':
app = Qt.QApplication(sys.argv)
w = MainWindow1()
w.show()
sys.exit(app.exec_())

Related

what do we need the Parent parameter in QMainWindow() for? [duplicate]

This question already has answers here:
In PyQT why somes widgets needs the "self" parameter before calling them, while others don't
(3 answers)
What is parent for in Qt?
(2 answers)
Closed 24 days ago.
I'm relatively new to Python and am currently working on the QtWidget. In my online course we created our own class that inherits from QtWidgets.QMainWindow. When creating the constructor, we created a parameter called Parent, what do we need it for? I've also read the official documentation, but I can't make any sense of it.
This is the code:
import sys
from qtpy import QtWidgets
from ui.mainwindow import Ui_MainWindow
app = QtWidgets.QApplication(sys.argv)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent = None):
super().__init__(parent)
self.setWindowTitle("Test")
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.button.clicked.connect(self.on_button_click)
def on_button_click(self):
self.weight = self.ui.weight.value()
self.height = self.ui.height.value()
if self.weight and self.height != 0:
self.rechnung = (self.weight) / (self.height ** 2)
self.ui.result.setText(f"Dein BMI hat einen Wert von {round(self.rechnung, 2)}")
else:
self.ui.result.setText("Deine eingaben dürfen keine 0 enthalten")
window = MainWindow()
window.show()
sys.exit(app.exec_())
we pass this parameter to the QtWidgets.QMainWindow() class, but for what?

Why does each menu entry print just the last value set, but putting in a seperate function works fine? [duplicate]

This question already has answers here:
Connecting slots and signals in PyQt4 in a loop
(3 answers)
Connecting multiples signal/slot in a for loop in pyqt
(3 answers)
Closed 7 months ago.
I came across this issue when making 'QMenu' actions in a loop and assigning a connection with them. Here is an example:
import sys
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
mbar = self.menuBar()
file_menu = mbar.addMenu("File")
animals = ['Dog','Badger','Bear','Fox']
for animal in animals:
ac = file_menu.addAction(animal)
ac.triggered.connect(lambda: print(animal))
'''Even though each action is assigned a seperate connection with the current animal,
only the last animal is ever printed. Why?'''
def main():
app = QtWidgets.QApplication([sys.argv])
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
The last variable in the loop, 'Fox', is printed for all menu entries. The solution mentioned here is to use the QMenu triggered signal instead, allowing you to store the data in the action and access it that way. Like this:
import sys
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
mbar = self.menuBar()
file_menu = mbar.addMenu("File")
animals = ['Dog','Badger','Bear','Fox']
for animal in animals:
ac = file_menu.addAction(animal)
ac.setData(animal)
file_menu.triggered.connect(lambda a: print(a.data()))
def main():
app = QtWidgets.QApplication([sys.argv])
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
This works fine but is a little annoying because to work in the real world I would have to implement some sort of check to make sure I was dealing with the right sort of action, for example by making a dataclass to hold the animal and checking for that dataclass instance. But then I discovered that the following approach also works:
import sys
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
mbar = self.menuBar()
self.file_menu = mbar.addMenu("File")
animals = ['Dog','Badger','Bear','Fox']
for animal in animals:
self.make_menu_entry(animal)
def make_menu_entry(self, animal):
ac = self.file_menu.addAction(animal)
ac.triggered.connect(lambda: print(animal))
def main():
app = QtWidgets.QApplication([sys.argv])
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
So now I'm thinking that this a scope problem, but I don't understand it. Can anyone explain what's happening?

buttonClicked() method for button on QMessageBox [duplicate]

This question already has answers here:
How to capture button click from customized QMessageBox?
(3 answers)
Closed 2 years ago.
I want to call "removeDuplicate" method when 'Ok' button on QMessageBox is clicked. But when I click the button the method doesn't execute. What should I do?
Here is my code snippet :
def removeDuplicate(self):
curItem = self.listWidget_2.currentItem()
self.listWidget_2.takeItem(curItem)
def error_popup(self):
msg=QtWidgets.QMessageBox()
msg.setText("You can't select more than one wicket-keeper.")
msg.setWindowTitle(" ")
msg.setIcon(QtWidgets.QMessageBox.Critical)
x = msg.exec_()
msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
msg.buttonClicked.connect(self.removeDuplicate)
Try it:
import sys
from PyQt5.Qt import *
from PyQt5 import QtGui, QtCore, QtWidgets
class Window(QWidget):
def __init__(self):
super().__init__()
self.error_popup()
def removeDuplicate(self):
print('def removeDuplicate(self): ...')
# curItem = self.listWidget_2.currentItem()
# self.listWidget_2.takeItem(curItem)
def error_popup(self):
msg = QMessageBox.critical(
self,
'Title',
"You can't select more than one wicket-keeper",
QMessageBox.Yes | QMessageBox.Cancel
)
if msg == QMessageBox.Yes:
# msg.buttonClicked.connect(self.removeDuplicate)
print('Ok')
self.removeDuplicate()
if __name__ == "__main__":
App = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(App.exec_())

PyQT4 TextBrowser Set Text Alighment [duplicate]

This question already has answers here:
Aligning text in QTextEdit?
(2 answers)
Closed 4 years ago.
I am doing some random choice picker where there's a place to display info user keyed in. (which I used text browser), How do I set the text to be always align center?
self.textBrowser.setText(newList + "\n\nanalyzing in ...")
QtTest.QTest.qWait(1000)
self.textBrowser.setText(newList + "\n\nanalyzing in ..." + "\n\n 3")
QTextBrowser Class Inherits: QTextEdit
QTextEdit::setAlignment(Qt::Alignment)
Sets the alignment of the current paragraph to a. Valid alignments are Qt::AlignLeft, Qt::AlignRight, Qt::AlignJustify and Qt::AlignCenter (which centers horizontally).
Sorry, I have PyQt5:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Win(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.i = 5
self.textBrowser = QtWidgets.QTextBrowser()
self.textBrowser.setAlignment(QtCore.Qt.AlignCenter) # <-------------
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.textBrowser)
self.setLayout(layout)
timer = QtCore.QTimer(self, interval=1000, timeout=self.print_out)
timer.start()
def print_out(self, string="Hello world!"):
self.textBrowser.append(string + "\n\nanalyzing in ...\n {}".format('----' * self.i))
self.i += 1
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
myWin = Win()
myWin.show()
sys.exit(app.exec_())

Why does my inherited widget not behave like superclass [duplicate]

This question already has an answer here:
QWidget does not draw background color
(1 answer)
Closed 4 years ago.
Observe the following code
#!/usr/bin/env python3
from PyQt5 import QtWidgets as w
class MyWidget(w.QWidget): pass
app = w.QApplication([])
frame = w.QWidget()
grid = w.QGridLayout()
frame.setLayout(grid)
w1 = MyWidget()
w2 = w.QWidget()
grid.addWidget(w1)
grid.addWidget(w2)
w1.setStyleSheet("background-color: red")
w2.setStyleSheet("background-color: red")
frame.show()
app.exec_()
The resulting app doesn't produce two identical red widgets. Qt documentation implies that things like stylesheets should work just perfectly with subclassed widgets. What's wrong here?
As they comment in this post and this post so that the inheriting classes you must overwrite paintEvent():
#!/usr/bin/env python3
from PyQt5 import QtGui, QtWidgets
class MyWidget(QtWidgets.QWidget):
def paintEvent(self, event):
opt = QtWidgets.QStyleOption()
opt.initFrom(self)
p = QtGui.QPainter(self)
self.style().drawPrimitive(QtWidgets.QStyle.PE_Widget, opt, p, self)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
frame = QtWidgets.QWidget()
grid = QtWidgets.QGridLayout(frame)
for w in (MyWidget(), QtWidgets.QWidget()):
grid.addWidget(w)
w.setStyleSheet("background-color: red")
frame.resize(640, 480)
frame.show()
sys.exit(app.exec_())

Categories

Resources