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?
Related
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?
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_())
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_())
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_())
This question already has answers here:
What does 'super' do in Python? - difference between super().__init__() and explicit superclass __init__()
(11 answers)
Closed 7 years ago.
#!/usr/bin/python
import sys
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__() # what the meaning of this line
self.initUI()
def initUI(self):
lbl1 = QtGui.QLabel('ZetCode', self)
lbl1.move(15, 10)
lbl2 = QtGui.QLabel('tutorials', self)
lbl2.move(35, 40)
lbl3 = QtGui.QLabel('for programmers', self)
lbl3.move(55, 70)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Absolute')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
super() function invokes the parent constructor. In case of earlier version of python, we have to manually decide the parent class whose constructor have to be invoked, in case when child class inherits from multiple class. In new style classes, super() does this task to avoid diamond problem on inheritance. Refer to super() doc in python documentation.