Connecting qpushbutton to lambda [duplicate] - python

This is entire my code:
import sys
from PySide2.QtCore import Qt
from PySide2.QtWidgets import (
QApplication,
QHBoxLayout,
QLabel,
QMainWindow,
QPushButton,
QVBoxLayout,
QWidget,
)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
v = QVBoxLayout()
h = QHBoxLayout()
for a in range(10):
button = QPushButton(str(a))
button.clicked.connect(lambda checked, a=a: self.button_clicked(a)) # error here
h.addWidget(button)
v.addLayout(h)
self.label = QLabel("")
v.addWidget(self.label)
w = QWidget()
w.setLayout(v)
self.setCentralWidget(w)
def button_clicked(self, n):
self.label.setText(str(n))
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
When I run this code, I get a window like this:
Below the buttons, there is a QLabel, and I want when I click on any button, the button's label will refer to this QLabel, but I get a bunch of confusing errors in the terminal. What's wrong with my code, help me, thanks.

The clicked signal is overload so it accepts 2 signatures where it can send a bool or not. The default signature depends on the library, in this case it seems that PySide2 by default does not send the "checked" parameter, unlike PyQt5 that does.
The solution is to indicate the signature:
button.clicked[bool].connect(lambda checked, a=a: self.button_clicked(a))

Related

Menu item now showing in PyQT6 GUI

I'm creating a basic pyqt6 application using the QMainWindow Class.
My code is basic. I create a basic window, but whenever I execute this code, I do not see any menu:
from PyQt6.QtWidgets import QStatusBar, QApplication, QWidget, QMainWindow, QVBoxLayout, QScrollBar, \
QToolButton
import sys
# There are THREE different window type classes
# that we can choose from:
# QWidget, QMainWindow, QDialog
class Window(QMainWindow):
def __init__(self):
super().__init__()
# Manages GUI Applications Control Flow
# and main settings..
app = QApplication([])
window = Window()
window.setWindowTitle("My 1st App")
window.statusBar().showMessage("Status Bar Message")
window.menuBar().addMenu("Menu 1")
window.show()
sys.exit(app.exec())
What am I doing wrong?
Why isn't "MENU 1" showing in the GUI?

A blank window after overriding PyQt5.QWidget.__init__()

I am learning to write PyQt5 codes.When I tried to code a subclass extented from PyQt5.QWidget and to override its constructor function, I found that the new code didn't work.(A blank window without anything you coded would show up.)It seems that the program stopped after "super().init()".Even I think the constructor don't run.But when I put the lines except "super()._init()" in a overridden function "PyQt5.Qwidegt.show()", it runs well.I am wondering why.It is quite pluzzing for a green hand.
The codes are as followed:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout,
QPushButton
class VBoxLayoutWindow(QWidget):
def __int__(self):
super().__init__()
self.resize(300, 300)
self.setWindowTitle("VBox Layout")
layout = QVBoxLayout()
button1 = QPushButton("Button1")
button2 = QPushButton("Button2")
button3 = QPushButton("Button3")
layout.addWidget(button1)
layout.addWidget(button2)
layout.addWidget(button3)
layout.addStretch(2)
self.setLayout(layout)
app = QApplication(sys.argv)
w = VBoxLayoutWindow()
w.show()
app.exec_()

PyQt5-How can i send inputs received from the user via the UI to the function [duplicate]

hello world i am trying to get a QLineEdit to work as a user Input witch they are suppose to type in a song name. after the song name is entered i am wanting that song to start playing after the click the play button everything is working fine other then the part where they can type in what ever song they want in that folder. the problem is im not sure on how to make the QlineEdit word and update everytime someone thing is entered into the text box here is my code hopefully someone can help me out Thanks in advance!
import sys
import webbrowser
import random
import time
import os
import subprocess
from PyQt4.QtCore import QSize, QTimer, SIGNAL
from PyQt4.QtGui import QApplication,QScrollBar,QLineEdit , QDialog , QFormLayout ,QGraphicsRectItem , QMainWindow, QPushButton, QWidget, QIcon, QLabel, QPainter, QPixmap, QMessageBox, QAction, QKeySequence, QFont, QFontMetrics, QMovie
from PyQt4 import QtGui
import vlc
#----|Imports End|----#
class UIWindow(QWidget):
def __init__(self, parent=None):
super(UIWindow, self).__init__(parent)
self.resize(QSize(400, 450))
self.Play = QPushButton('Play', self)
self.Play.resize(100,40)
self.Play.move(45, 100)#
self.Pause = QPushButton('Pause', self)
self.Pause.resize(100,40)
self.Pause.move(260, 100)#
self.Tbox = QLineEdit('Song name',self)
self.Tbox.resize(400,25)
self.Tbox.move(0,50)
self.Play.clicked.connect(self.PlayB)
self.Pause.clicked.connect(self.PauseB)
self.Flask = vlc.MediaPlayer("C:\Users\Matt\Music\\"+str(self.Tbox.text())+".mp3")
def PlayB(self):
self.Flask.play()
def PauseB(self):
self.Flask.stop()
class MainWindow(QMainWindow,):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setGeometry(745 ,350 , 400, 450)
self.setFixedSize(400, 450)
self.startUIWindow()
def startUIWindow(self):
self.Window = UIWindow(self)
self.setWindowTitle("HELP ME!")
self.setCentralWidget(self.Window)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
sys.exit(app.exec_())
You can easily get text with QLineEdit.text() method.
Or same way set text with QLineEdit.setText() method
If you want to connect it to QTextEdit You can connect it with .textChanged signal which is emited from QTextEdit everytime text changes.
The same way how you use .clicked signal you can use this one as:
QTextEdit.textChanged.connect(your_method_to_put_text_somewhere_else)

How to keep PyQt5 responsive when calling gnuplot?

I am trying to create plots with a Python GUI and gnuplot.
I am generating the code in Python and send it to gnuplot.
This basically works with piping data to gnuplot, but:
Disadvantages:
the Python program is blocked until you close gnuplot
you have to load/start gnuplot again and again everytime you're making a plot which seems to take annoying extra time (on slow computers)
My questions:
how to keep the Python program responsive?
is there a way to start gnuplot once and keep it running?
how to just update the gnuplot terminal if there is a new plot?
Thank you for hints and links.
Here is my code:
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPlainTextEdit, QPushButton
import subprocess
class MyWindow(QWidget):
def __init__(self):
super(MyWindow,self).__init__()
self.setGeometry(100,100,400,200)
self.myTextEdit = QPlainTextEdit()
self.myTextEdit.setPlainText("plot sin(x)")
self.button = QPushButton('Plot code',self)
self.button.clicked.connect(self.on_button_click)
vbox = QVBoxLayout(self)
vbox.addWidget(self.myTextEdit)
vbox.addWidget(self.button)
self.setLayout(vbox)
#pyqtSlot()
def on_button_click(self):
gnuplot_str = self.myTextEdit.document().toPlainText() + "\n"
gnuplot_path = r'C:\Programs\gnuplot\bin\gnuplot.exe'
plot = subprocess.Popen([gnuplot_path,'-p'],stdin=subprocess.PIPE)
plot.communicate(gnuplot_str.encode())
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
Instead of using subprocess you must use QProcess which is friendly to the Qt event loop as I show below:
import sys
from PyQt5.QtCore import QProcess, pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPlainTextEdit, QPushButton
class MyWindow(QWidget):
def __init__(self):
super(MyWindow,self).__init__()
self.setGeometry(100,100,400,200)
self.myTextEdit = QPlainTextEdit()
self.myTextEdit.setPlainText("plot sin(x)")
self.button = QPushButton('Plot code',self)
self.button.clicked.connect(self.on_button_click)
vbox = QVBoxLayout(self)
vbox.addWidget(self.myTextEdit)
vbox.addWidget(self.button)
gnuplot_path = r'C:\Programs\gnuplot\bin\gnuplot.exe'
self.process = QProcess(self)
self.process.start(gnuplot_path, ["-p"])
#pyqtSlot()
def on_button_click(self):
gnuplot_str = self.myTextEdit.document().toPlainText() + "\n"
self.process.write(gnuplot_str.encode())
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())

How do I make my QTableWidget class (any class) update/refresh itself?

I am making a gui using pyqt4. When I insert data from sqlite into my qtablewidget table, it will only update itself once I have closed the program and reopened it. How can I have the program update itself automatically (refresh the class) after inserting/deleting or changing the data in anyway?
Since I am not sure how you are implementing your code, maybe the following code helps you.
#!/usr/bin/python
import sys
from PyQt4.QtGui import QWidget, QPushButton, QMainWindow, QTableWidget,QTableWidgetItem, QVBoxLayout, QApplication
from PyQt4.QtCore import Qt
class MyMainWindow(QMainWindow):
def __init__(self, parent=None):
"""
"""
super(MyMainWindow,self).__init__(parent)
self.setWidgets()
def setWidgets(self, ):
vBox = QVBoxLayout()
mainFrame = QWidget()
self._pressButton = QPushButton("Update Table",self)
self._pressButton.clicked.connect(self.updateTable)
self._table = QTableWidget(self)
self._table.setRowCount(3)
self._table.setColumnCount(3)
vBox.addWidget(self._pressButton)
vBox.addWidget(self._table)
mainFrame.setLayout(vBox)
self.setCentralWidget(mainFrame)
def updateTable(self, ):
i = self._table.currentRow()
if i == -1:
i=0
self._table.insertRow(i)
self._table.setItem(i,0,QTableWidgetItem("Test"))
if __name__ == '__main__':
qApp = QApplication(sys.argv)
MainWindow = MyMainWindow()
MainWindow.show()
sys.exit(qApp.exec_())
Cheers

Categories