This question already has answers here:
Lambda in a loop [duplicate]
(4 answers)
Connecting slots and signals in PyQt4 in a loop
(3 answers)
Using lambda expression to connect slots in pyqt
(4 answers)
Closed 3 years ago.
I want to create multiple buttons by a for loop.
Pressing on the buttons call same function but transfer a different parameters.
def someFunction(self):
buttons = [None] * 8
for i in range(8):
buttons[i] = QPushButton(self)
buttons[i].clicked.connect(self.function(i))
def function(self, i):
print(i)
I expect the output of buttons[i] to be i but the output always 7
Try it:
from PyQt5.QtWidgets import *
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout(self)
self.someFunction()
def someFunction(self):
# buttons = [None] * 8
for i in range(8):
button = QPushButton("Button {}".format(i), self)
button.clicked.connect(lambda ch, i=i: self.function(i)) # < ---
self.layout.addWidget(button)
def function(self, i):
print(i)
if __name__ == '__main__':
app = QApplication([])
mainapp = MainWindow()
mainapp.show()
app.exec_()
Related
This question already has answers here:
Return value from button click
(2 answers)
PySide: Returning a value from a slot
(3 answers)
Closed 1 year ago.
I cannot figure out, how I'm able to get variable (dictionary) out from the class.
When the button "ETSI" is clicked, the code will get all inputs from the GUI window (type fields and checkboxes) that the user provided and creates a dictionary out of that data.
The problem is that I cannot figure out how to return that dictionary, from the class.
CODE:
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5 import uic
import sys
class UI(QWidget):
def __init__(self):
super().__init__()
# --- Init window ------#
uic.loadUi("DesignerWindow/window.ui", self)
# --- Button action ------#
button = self.findChild(QPushButton, 'etsiButton')
# ---- Define action for the button ---#
button.clicked.connect(self.clicked_btn)
def clicked_btn(self):
resultList = {}
# Sijainti
sijaintiInput = self.sijaintiInput.text()
if sijaintiInput != "":
resultList ["sijainti"] = sijaintiInput
# Hinta
hintaInputMin = self.hintaInputMin.text()
if hintaInputMin != "":
resultList ["hintaMin"] = hintaInputMin
hintaInputMax = self.hintaInputMax.text()
if hintaInputMax != "":
resultList ["hintaMax"] = hintaInputMax
# Asuintilojen pinta-ala
atpInputMin = self.atpInputMin.text()
if atpInputMin != "":
resultList ["atpMin"] = atpInputMin
return resultList
# Execute
app = QApplication([])
window = UI()
window.show()
sys.exit(app.exec_())
This question already has answers here:
Python: Pass extra arguments to callable
(2 answers)
Closed 1 year ago.
I am overriding the QWidget.mousePressEvent like this:
widget = QtWidgets.QWidget()
widget.mousePressEvent = my_function
def my_function(QMouseEvent):
print('Mouse Pressed')
But my question is, how do I now pass it a variable? I need something like this:
for index in range(10):
widget = QtWidgets.QWidget()
widget.mousePressEvent = my_function(index)
def my_function(QMouseEvent, index):
print(index)
Use functools.partial
from functools import partial
def my_function(index, QMouseEvent):
print(index)
for index in range(10):
widget = QtWidgets.QWidget()
widget.mousePressEvent = partial(my_function, index)
Or use lambda
widget.mousePressEvent = lambda: event, index=index: my_function(index, event)
Notice that optional lambda argument used for capturing index by value.
This question already has answers here:
Qt - updating main window with second thread
(3 answers)
How do I create a Window in different QT threads?
(4 answers)
Closed 1 year ago.
I am trying to messing up with something and I am not able to create a widget using threading.
Could someone take a look at my test script and let me know why this does not work?
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import *
import threading
import time
class Main(QMainWindow):
def __init__(self):
super(Main, self).__init__()
self._build_ui()
main_thread = threading.Thread(target=self.thread_function)
main_thread.start()
def thread_function(self):
i = 0
while True:
message = "Message number: {}".format(i)
print (message)
self.create_message_widget(message)
i+=1
time.sleep(1)
def create_message_widget(self, message):
print ("Testing 3")
self.label = QLabel(self)
self.label.setText(message)
self.verticalLayout.addWidget(self.label)
def _build_ui(self):
self.setWindowTitle("Testing Window")
# set the central widget and main layout
self.centralWidget = QWidget(self)
self.verticalLayout = QVBoxLayout(self)
self.setCentralWidget(self.centralWidget)
self.centralWidget.setLayout(self.verticalLayout)
self.button = QPushButton("Run")
self.button.clicked.connect(lambda: self.create_message_widget("Testing 1"))
# adding widgets to the window
self.verticalLayout.addWidget(self.button)
self.create_message_widget("Testing 2")
self.create_message_widget("Testing 2")
self.create_message_widget("Testing 2")
# show main window
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Main()
sys.exit(app.exec())
The following script shows 3 functions where I did few Testing X.
You can notice the Testing 2 are created fine.
When we click the button we can see Testing 1 which is populated by button press.
In thread_function I call create_message_widget function and I thought that should automatically create widget every 1 sec but it does not do anything. Could someone explain why and if this is possible to make it works?
This question already has answers here:
Creating PyQt5 buttons in a loop: all buttons trigger the same callback
(1 answer)
Connecting slots and signals in PyQt4 in a loop
(3 answers)
Closed 2 years ago.
class MainMenu(QWidget):
def __init__(self):
# QWiget constructor
super().__init__()
self.initUI()
def initUI(self):
self.buttons = (QPushButton('Uebergang'), QPushButton('Scherung'), QPushButton('Wippe'))
self.layout = QVBoxLayout()
for button in self.buttons:
self.layout.addWidget(button)
func = lambda : self.openMenu(button.text())
button.clicked.connect(func)
self.setLayout(self.layout)
self.show()
def openMenu(self, Menu):
print(Menu)
When I click on any of the three buttons it always prints "Wippe". I don't understand why. I know this question has been answered before but the answers didn't solve my problem.
This question already has answers here:
Understanding Python super() with __init__() methods [duplicate]
(7 answers)
Closed 4 years ago.
I have a PyQt5 application built that looks like so (I know I have a lot of imports, I am learning so I want complete freedom at the moment):
import sys
from PyQt5.QtGui import *
from PyQt5.QWidgets import *
from PyQt5.QtCore import *
class Menu(QMainWindow):
def __init__(self)
super().__init__()
#create bar
bar = self.menuBar()
#create bar menus
file = bar.addMenu("File")
about = bar.addMenu("About")
#create actions
quit_action = QAction("&Quit", self)
quit_action.setShortcut('Ctrl+Q')
about_action = QAction("&About...", self)
#add actions
file.addAction(quit_action)
about.addAction(about_action)
#what to do with actions
quit_action.triggered.connect(self.quit_func)
about_action.triggered.connect(self.about_func)
#window properties
self.setWindowTitle("Hello World")
self.resize(600, 400)
self.show()
def quit_func(self):
sys.exit()
def about_func(self):
pass
class About(QWidget):
def __init__(self):
super().__init__(parent)
#widgets
self.l1 = QLabel('Hello World')
self.l1.setAlignment(Qt.AlignCenter)
self.l2 = QLabel('Description of the Application')
self.l2.setAlignment(Qt.AlignCenter)
#horiz box
h_box = QHBoxLayout()
h_box.addStretch()
h_box.addWidget(self.l2)
h_box.addStretch()
#vert box
v_box = QVBoxLayout()
v_box.addWidget(self.l1)
v_box.addLayout(h_box)
v_box.addStretch()
self.setLayout(v_box)
#window properties
self.setWindowTitle("About Hello World")
self.setFixedSize(250,150)
self.show()
if not QApplication.instance()
app = QApplication(sys.argv)
else:
app = QApplication.instance()
main = Menu()
main.show()
sys.exit(app.exec())
I want the about_func() function to call to the About() class, so I can open a window separate from my Main Window created by Menu() class.
This code is throwing the error:
TypeError: QMainWindow(parent: QWidget = None, flags: Union[Qt.WindowFlags, Qt.WindowType] = Qt.WindowFlags()): argument 1 has unexpected type 'sip.wrappertype'
in reference to the super().__init__() in line 9.
How could I implement this in a working fashion? Feel free to criticize any aspect of my code.
(Edited to clarify question)
From your code it's not very clear if you are using Python 2 or 3, anyway, the basic syntax of super is:
super(yourClass, instance).method(args)
So, in your case they are both wrong :-) The first one should be:
class Menu(QMainWindow):
def __init__(self, parent=None):
super(Menu, self).__init__(parent)
Also, from Python3 the arguments of super() can be omitted, so the second example could be:
class About(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
Read carefully the Built-in Functions. I know it's a long page, but it contains some of the fundamentals of Python, and studying/understanding them is almost mandatory.