Updating PyQT label - python

I'm attempting to use a timer for scheduling to update certain values across the grid. Below is the example where I am attempting to update a label based on a timed event. I've successfully gotten it to call the function but I cannot update the label. Any thoughts?
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import QtCore, QtGui, QtWidgets
class App(QWidget):
def __init__(self):
super().__init__() #these values change where the main window is placed
self.title = 'This is my title'
self.left = 400
self.top = 400
self.width = 300
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# call the gridlayout function
self.createGridLayout()
self.time_label.text = 'change the value'
windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)
self.show() #this sets the main window to the screen size
def createGridLayout(self):
time = self.getTime()
self.time_label = QLabel(time, self)
self.horizontalGroupBox = QGroupBox()
layout = QGridLayout()
layout.addWidget(QPushButton('1'),0,0)
layout.addWidget(QPushButton(time),0,1)
layout.addWidget(self.time_label,0,2)
self.horizontalGroupBox.setLayout(layout)
def getTime(self):
time = QTime.currentTime().toString()
return time
def updateTime():
App.time = QTime.currentTime().toString()
time = QTime.currentTime().toString()
print("Time: " + time)
# self.time_label = 'change the value'
# self..layout.time_label = 'asdf'
return time
def main():
app = QApplication(sys.argv)
ex = App()
timer=QtCore.QTimer()
timer.timeout.connect(App.updateTime)
timer.start(1000)
sys.exit(app.exec_())
if __name__ == '__main__':
# App.main()
main()

Your code has some errors, if you want to use an attribute of the class with the reserved word self, this method must be a method of the class, for this it changes:
def updateTime():
to
def updateTime(self):
If you want to change the text of a QLabel you must use its setText().
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class App(QWidget):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent) # these values change where the main window is placed
self.title = 'This is my title'
self.left = 400
self.top = 400
self.width = 300
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# call the gridlayout function
self.createGridLayout()
self.time_label.text = 'change the value'
windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)
self.show() # this sets the main window to the screen size
def createGridLayout(self):
time = self.getTime()
self.time_label = QLabel(time, self)
self.horizontalGroupBox = QGroupBox()
layout = QGridLayout()
layout.addWidget(QPushButton('1'), 0, 0)
layout.addWidget(QPushButton(time), 0, 1)
layout.addWidget(self.time_label, 0, 2)
self.horizontalGroupBox.setLayout(layout)
def getTime(self):
time = QTime.currentTime().toString()
return time
def updateTime(self):
time = QTime.currentTime().toString()
print("Time: " + time)
self.time_label.setText(time)
return time
def main():
app = QApplication(sys.argv)
ex = App()
timer = QTimer()
timer.timeout.connect(ex.updateTime)
timer.start(1000)
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Related

Bring to the front the MainWindow in Pyqt5

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"
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()

How to go through next and previous list items with buttons?

I have a list:
files = ["image1.png", "image2.png", "image3.png", "image4.png", "image5.png", "image6.png"]
And PyQt5 buttons and a label:
How can I have the first item of the list on the label and go through the list one by one with the:
Next button (click, image2.png, click, image3.png, click, image4.png...)
Previous button (click, image3.png, click, image2.png, click, image1.png...)
And the label should update accordingly.
I've tried all day and searched for answers but couldn't get it to work. This could help maybe, my skills weren't enough to utilize the advice, though.
All the code to create the above window with buttons:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self._files = deque()
self._filesCount = len(self._files)
self._setupUI()
self._connectSignalsSlots()
def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button = QPushButton('Print Files List', self)
button.move(100,70)
button.clicked.connect(self.loadFiles)
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button = QPushButton('Print Next Filename', self)
button.move(160,110)
button.clicked.connect(self.nextFilename)
label = QLabel('image1.png (should be first of the list, \n and update with button presses)', self)
label.move(35,140)
button = QPushButton('Print Previous Filename', self)
button.move(10,110)
button.clicked.connect(self.previousFilename)
self.show()
#pyqtSlot()
def loadFiles(self):
files = ["image1.png", "image2.png", "image3.png", "image4.png", "image5.png", "image6.png"]
if len(files) > 0:
for file in files:
print(file)
def nextFilename(self):
print('nextFilenameButton click')
def previousFilename(self):
print('previousFilenameButton click')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
The solution is to handle an index (or cursor) that serves to obtain the filename. And that index must be modified through the buttons
import sys
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QGridLayout, QLabel, QPushButton, QWidget
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self._current_index = 0
self._filenames = []
self.previous_button = QPushButton("Previous")
self.next_button = QPushButton("Next")
self.print_button = QPushButton("Print")
self.label = QLabel()
lay = QGridLayout(self)
lay.addWidget(self.previous_button, 0, 0)
lay.addWidget(self.next_button, 0, 1)
lay.addWidget(self.print_button, 0, 2)
lay.addWidget(self.label, 1, 0, 1, 3)
self.previous_button.clicked.connect(self.handle_previous)
self.next_button.clicked.connect(self.handle_next)
self.print_button.clicked.connect(self.handle_print)
self._update_button_status(False, True)
self.load_files()
def load_files(self):
self._filenames = [
"image1.png",
"image2.png",
"image3.png",
"image4.png",
"image5.png",
"image6.png",
]
self.current_index = 0
def handle_next(self):
self.current_index += 1
def handle_previous(self):
self.current_index -= 1
def handle_print(self):
for filename in self._filenames:
print(filename)
#property
def current_index(self):
return self._current_index
#current_index.setter
def current_index(self, index):
if index <= 0:
self._update_button_status(False, True)
elif index >= (len(self._filenames) - 1):
self._update_button_status(True, False)
else:
self._update_button_status(True, True)
if 0 <= index < len(self._filenames):
self._current_index = index
filename = self._filenames[self._current_index]
pixmap = QPixmap(filename)
self.label.setPixmap(pixmap)
def _update_button_status(self, previous_enable, next_enable):
self.previous_button.setEnabled(previous_enable)
self.next_button.setEnabled(next_enable)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Widget()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
Note: Having 2 methods with the same name is useless since in python only the last implementation will be used.

PyQt5 Switch between window after time in a loop

i use the code below, found on stackoverflow. i want to build a loop which getting started with a button on the main window. After clicked window2 should open for 30 seconds. then window3 should open for 30 seconds. then window2 should open and so on.
i make a slide methode but it wont work.
i try it with the window2() and window3() and slide() methode
what is my target?
i want a slideshow with the two window(window2 & window3) that alternate.
not more but it is an endless loop
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QToolTip, QMessageBox, QLabel)
class Window2(QMainWindow): # <===
def __init__(self):
super().__init__()
self.setWindowTitle("Window22222")
class Window3(QMainWindow): # <===
def __init__(self):
super().__init__()
self.setWindowTitle("Window333333")
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("Start", self)
self.pushButton.move(275, 200)
self.pushButton.setToolTip("<h3>Start the Session</h3>")
self.pushButton.clicked.connect(self.window2)
self.pushButton1 = QPushButton("Start", self)
self.pushButton1.move(20, 20)
self.pushButton1.setToolTip("<h3>Start the Session</h3>")
self.pushButton1.clicked.connect(self.slide)
self.main_window()
def main_window(self):
self.label = QLabel("Manager", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.show()
def window2(self): # <===
self.w2 = Window2()
self.w2.show()
time.sleep(5)
self.w3 = Window3()
self.w3.show()
self.w2.hide()
self.window3()
#self.hide()
def window3(self): # <===
self.w3 = Window3()
self.w3.show()
time.sleep(5)
self.w2 = Window2()
self.w2.show()
self.w3.hide()
self.window2()
#self.hide()
def slide(self):
print ("slide")
self.window2()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
sys.exit(app.exec())
Try it:
import sys
#import time
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QToolTip, QMessageBox, QLabel)
class Window2(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Window 22222")
class Window3(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Window 333333")
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "First Window"
self.top, self.left, self.width, self.height = 100, 100, 680, 500
self.flag = ...
self.pushButton = QPushButton("Start", self)
self.pushButton.move(275, 200)
self.pushButton.setToolTip("<h3>Start the Session</h3>")
self.pushButton.clicked.connect(lambda: self.start_slide(True)) #(self.window2)
self.pushButton1 = QPushButton("Start", self)
self.pushButton1.move(20, 20)
self.pushButton1.setToolTip("<h3>Start the Session</h3>")
self.pushButton1.clicked.connect(lambda: self.start_slide(False))
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
self.main_window()
self.w2 = Window2()
self.w3 = Window3()
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.viewWindows)
def start_slide(self, flag):
self.timer.stop()
self.w3.hide()
self.w2.hide()
if flag: self.w2.show()
else: self.w3.show()
self.flag = not flag
self.timer.start(5000)
def viewWindows(self):
if self.flag:
self.w2.show()
self.w3.hide()
else:
self.w3.show()
self.w2.hide()
self.flag = not self.flag
def closeEvent(self, event):
self.w2.close()
self.w3.close()
self.close()
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
def main_window(self):
self.label = QLabel("Manager", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())

Control window and Display window

I need two PyQt windows to run in the same time on a multiple display machine: one screen for display and the other for input.
In the following example i'm trying to have a simple window with a button and another window with a label. When i push the button, the other windows label text should change:
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget, QDialog, QInputDialog,QDesktopWidget,QVBoxLayout,QPushButton,QMainWindow,QAction,QFileDialog,QGroupBox,QGridLayout,QLabel
class Control_Pannel(QWidget):
def __init__(self):
super().__init__()
self.title = 'Main Control Pannel'
self.left = 10
self.top = 10
self.width = 640
self.height = 400
self.text = "Display text"
self.InitializeUI()
def InitializeUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left,self.top,self.width,self.height)
self.inputBox = QGroupBox("Display")
layout = QGridLayout()
layout.setColumnStretch(1, 4)
layout.setColumnStretch(2, 4)
button = QPushButton('Push here to change text')
layout.addWidget(button,0,0)
button.clicked.connect(self.on_click)
self.inputBox.setLayout(layout)
windowLayout = QVBoxLayout()
windowLayout.addWidget(self.inputBox)
self.setLayout(windowLayout)
self.show()
app = QApplication(sys.argv)
ex=InputWindows()
sys.exit(app.exec_())
#pyqtSlot()
def on_click(self):
InputWindows.text = "Modified text after button push"
print(InputWindows.text)
InputWindows.update()
##???? here i don't know how to make the changes be reflected in the other window, even if when i print the .text attribute it seems to have changed.
class InputWindows(QDialog):
def __init__(self):
super().__init__()
self.title = 'Display Pannel'
self.left = 5
self.top = 5
self.width = 300
self.height = 300
self.text = "Original Text"
self.InitializeUI()
def InitializeUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left,self.top,self.width,self.height)
self.createDisplayGridLayout()
windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)
self.show()
def createDisplayGridLayout(self):
self.horizontalGroupBox = QGroupBox("Grid")
layout = QGridLayout()
layout.setColumnStretch(1, 4)
layout.setColumnStretch(2, 4)
self.label = QLabel(self.text)
layout.addWidget(self.label,0,0)
if __name__=='__main__':
app=QApplication(sys.argv)
ex=Control_Pannel()
sys.exit(app.exec_())
With InputWindows.update() i'm getting that first argument of unbound method must have a type QWidget and if i try InputWindows.label.update() i'm getting type object inputwindows has no attribute label
InputWindows is a class, it is an abstraction so you generally have to create an object, I ask you: if you have n Windows InputWindows, to which window would you update the text ?, we would not know, so by simple logic we see that it is wrong to do it. On the other hand, consider each class as a black box where it is stimulated by inputs, and outputs are obtained, in your case Control_Pannel must have an output: the new text, but that output is asynchronous since it changes and must be used when changing , and that in Qt is a signal, so we must create it. On the other hand, InputWindows must receive the information to create a slot that updates the text in the QLabel as shown below:
import sys
from PyQt5 import QtCore, QtWidgets
class Control_Pannel(QtWidgets.QWidget):
sendSignal = QtCore.pyqtSignal(str)
def __init__(self):
super().__init__()
self.title = 'Main Control Pannel'
self.left = 10
self.top = 10
self.width = 640
self.height = 400
self.text = "Display text"
self.InitializeUI()
def InitializeUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left,self.top,self.width,self.height)
self.inputBox = QtWidgets.QGroupBox("Display")
layout = QtWidgets.QGridLayout()
layout.setColumnStretch(1, 4)
layout.setColumnStretch(2, 4)
button = QtWidgets.QPushButton('Push here to change text')
layout.addWidget(button,0,0)
button.clicked.connect(self.on_click)
self.inputBox.setLayout(layout)
windowLayout = QtWidgets.QVBoxLayout(self)
windowLayout.addWidget(self.inputBox)
#QtCore.pyqtSlot()
def on_click(self):
text = "Modified text after button push"
self.sendSignal.emit(text)
class InputWindows(QtWidgets.QDialog):
def __init__(self):
super().__init__()
self.title = 'Display Pannel'
self.left = 5
self.top = 5
self.width = 300
self.height = 300
self.InitializeUI()
self.setText("Original Text")
#QtCore.pyqtSlot(str)
def setText(self, text):
self.label.setText(text)
def InitializeUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left,self.top,self.width,self.height)
self.createDisplayGridLayout()
windowLayout = QtWidgets.QVBoxLayout(self)
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)
def createDisplayGridLayout(self):
self.horizontalGroupBox = QtWidgets.QGroupBox("Grid")
layout = QtWidgets.QGridLayout()
layout.setColumnStretch(1, 4)
layout.setColumnStretch(2, 4)
self.label = QtWidgets.QLabel()
layout.addWidget(self.label, 0, 0)
self.horizontalGroupBox.setLayout(layout)
if __name__=='__main__':
app = QtWidgets.QApplication(sys.argv)
ex1 = Control_Pannel()
ex1.show()
ex2 = InputWindows()
ex2.show()
ex1.sendSignal.connect(ex2.setText)
sys.exit(app.exec_())

Clear Button PyQt5

I have been trying to build a simple GUI with:
A QLineEdit where the user writes a string
A QPushButton that clears whatever the user writes in the above lineedit every time I click on it.
My issue is in the second one. I have been trying to solve it by looking at solutions online but they weren't really useful so far. Can anyone give a hint on how to proceed?
Here is my code:
import sys
from PyQt5.QtWidgets import QWidget, QLineEdit
from PyQt5.QtWidgets import QLabel, QPushButton, QApplication
from PyQt5.QtCore import pyqtSlot
app = QApplication(sys.argv)
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'MyApp'
self.left = 10
self.top = 10
self.width = 800
self.height = 800
self.initUI()
self.show()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox for index number 1
self.nameLabel = QLabel(self)
self.nameLabel.setText('Insert something:')
self.nameLabel.move(20, 80)
self.textbox_index1 = QLineEdit(self)
self.textbox_index1.move(20, 100)
self.textbox_index1.resize(280, 40)
# Create a button in the window
self.buttonC1 = QPushButton('Clear', self)
self.buttonC1.move(300, 119)
# connect buttons "CLEAR" to function
self.buttonC1.clicked.connect(self.on_clickC1)
#pyqtSlot()
# Functions for the CLEAR buttons
def on_clickC1(self):
self.x1 = clearSearch1(self.textbox_index1.text(''))
return self.x1
def clearSearch1(self.x):
return self.x.clear()
if __name__ == '__main__':
app.aboutToQuit.connect(app.deleteLater)
ex = App()
sys.exit(app.exec_())
Thanks so much in advance,
Mattia
I do not understand what you are trying to do, the solution is simple, you must connect the clicked signal to the clear method directly without creating any other function:
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'MyApp'
self.left, self.top, self.width, self.height = 10, 10, 800, 800
self.initUI()
self.show()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox for index number 1
self.nameLabel = QLabel(self)
self.nameLabel.setText('Insert something:')
self.nameLabel.move(20, 80)
self.textbox_index1 = QLineEdit(self)
self.textbox_index1.move(20, 100)
self.textbox_index1.resize(280, 40)
# Create a button in the window
self.buttonC1 = QPushButton('Clear', self)
self.buttonC1.move(300, 119)
# connect buttons "CLEAR" to function
self.buttonC1.clicked.connect(self.textbox_index1.clear)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Categories