PyQt5 Switch between window after time in a loop - python

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

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 call the thread from a different function pyqt5

import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication, QPlainTextEdit, QApplication, QMainWindow, QLabel, QComboBox
from PyQt5.QtGui import QPixmap
from pynput import keyboard
from pynput.keyboard import Listener, Controller
import pyperclip as pc
keyboard = Controller()
class App(QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent)
#super().__init__()
label = QLabel(self)
pixmap = QPixmap('E:/copycat/new.png')
label.setPixmap(pixmap)
label.setGeometry(0,0,900,400)
self.title = 'COPYCAT'
self.left = 10
self.top = 10
self.width = 400
self.height = 140
self.initUI()
self.key()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
###########
combo = QComboBox(self)
shotcut_list = ["Key.f9","Key.f2","Key.f3","Key.f4","Key.f5","Key.f6","Key.f7","Key.f8","Key.f1","Key.f10","Key.f11","Key.f12"]
combo.addItems(shotcut_list)
global shortcut
global cptext
shortcut = combo.currentText()
combo.setGeometry(350, 120, 120, 30)
combo.activated[str].connect(self.onChanged)
# Create textbox
self.textbox = QPlainTextEdit(self)
self.textbox.move(20, 160)
self.textbox.setReadOnly(True)
self.textbox.resize(500,205)
self.setGeometry(70,70,540,388)
self.show()
def onChanged(self, text):
global shortcut
shortcut=text
def print_key(self,key):
if str(key) == shortcut:
cptext = pc.paste()
keyboard.type(cptext)
self.textbox.insertPlainText(cptext)
self.textbox.insertPlainText("\n")
def key(self):
listener = Listener(on_press=self.print_key)
listener.start()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = App()
#ex.key()
sys.exit(app.exec_())
The above code shows an error when I update the textbox from the print_key function
It shows this error:
Cannot queue arguments of type 'QTextBlock'
(Make sure 'QTextBlock' is registered using qRegisterMetaType()
Cannot queue arguments of type 'QTextCursor'
(Make sure 'QTextCursor' is registered using qRegisterMetaType()
The callback associated with on_press is executed in a secondary thread so your implementation is updating the GUI from a secondary thread which Qt prohibits, instead you should use the signals as they are thread-safe.
import sys
import threading
from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (
QApplication,
QComboBox,
QLabel,
QMainWindow,
QPlainTextEdit,
)
from pynput.keyboard import Listener, Controller
import pyperclip as pc
class KeyboardListener(QObject):
textChanged = pyqtSignal(str)
def __init__(self, shortcut, parent=None):
super().__init__(parent)
self._shortcut = shortcut
listener = Listener(on_press=self.handle_pressed)
listener.start()
self.mutex = threading.Lock()
#property
def shortcut(self):
return self._shortcut
def handle_pressed(self, key):
with self.mutex:
if str(key) == self.shortcut:
cptext = pc.paste()
self.textChanged.emit(cptext)
#pyqtSlot(str)
def update_shortcut(self, shortcut):
with self.mutex:
self._shortcut = shortcut
class App(QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent)
# super().__init__()
label = QLabel(self)
pixmap = QPixmap("E:/copycat/new.png")
label.setPixmap(pixmap)
label.setGeometry(0, 0, 900, 400)
self.title = "COPYCAT"
self.left = 10
self.top = 10
self.width = 400
self.height = 140
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
###########
combo = QComboBox(self)
shotcut_list = [
"Key.f9",
"Key.f2",
"Key.f3",
"Key.f4",
"Key.f5",
"Key.f6",
"Key.f7",
"Key.f8",
"Key.f1",
"Key.f10",
"Key.f11",
"Key.f12",
]
combo.addItems(shotcut_list)
shortcut = combo.currentText()
combo.setGeometry(350, 120, 120, 30)
self.textbox = QPlainTextEdit(self)
self.textbox.move(20, 160)
self.textbox.setReadOnly(True)
self.textbox.resize(500, 205)
self.setGeometry(70, 70, 540, 388)
self.keyboard = Controller()
self.listener = KeyboardListener(combo.currentText())
combo.activated[str].connect(self.listener.update_shortcut)
self.listener.textChanged.connect(self.handle_text_changed)
#pyqtSlot(str)
def handle_text_changed(self, text):
self.textbox.insertPlainText(text)
self.textbox.insertPlainText("\n")
self.keyboard.type(text)
def main():
app = QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

PyQt5 Custom Title Bar Doesn't Show

I am trying to make my first program. I'm hoping for custom dark mode design, and that requires me to make a custom title bar.
I copied the code for the title bar from someone else, it worked perfectly - custom movable window.
I have carefully merged it with my previous code, though title bar doesn't appear.
Now my guess is I have to call it at the end of my code, but it ends up with errors, as I'm not sure how to properly call it.
Note: removing the QtCore.Qt.FramelessWindowHint part is NOT the answer, as it just brings back the stock Win title bar, that's supposed to be hidden and replaced by dark title bar.
Part of code copied from: https://stackoverflow.com/a/44249552/12221725
Image:
import sys
from PyQt5 import QtGui, QtCore
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QTextEdit
#fCol = "#e0e0e0"
#bCol = "#212121"
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.layout = QHBoxLayout()
self.textArea = QTextEdit("Lorem ipsum...")
self.layout.addWidget(self.textArea)
self.textArea.setStyleSheet("QTextEdit {color:white;background-color:#212121;border-radius:+16px;}")
self.sans = QFont("Segoe UI",20)
self.textArea.setFont(self.sans)
self.btnLayout = QVBoxLayout()
self.btnLayout.addWidget(QPushButton("Open"))
self.btnLayout.addWidget(QPushButton("Setup"))
self.btnLayout.addWidget(QPushButton("Find"))
self.setStyleSheet("QPushButton {max-width:200px;color:#4fc3f7;background-color:#424242;border:2px solid #4fc3f7;border-radius:16px;font-size:35px;font-weight:bold;}" + "QPushButton:hover {color:#212121;background-color:#4fc3f7;}" + "QPushButton:pressed {color:white;background-color:#212121;border-color:white;}")
self.status = QTextEdit()
self.status.insertPlainText("Successfully loaded" + "\nOpen a file...")
self.status.setReadOnly(1)
self.status.setStyleSheet("QTextEdit {color:white;background-color:#212121;border-radius:+16px;font-size:14px;max-width:200px;}")
self.btnLayout.addWidget(self.status)
self.layout.addLayout(self.btnLayout)
self.setLayout(self.layout)
#self.setFixedSize(650, 320)
self.setFixedSize(800, 400)
self.setWindowTitle("Py Program")
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)# | QtCore.Qt.WindowStaysOnTopHint)
#self.layout.setContentsMargins(0,0,0,0)
#self.layout.addStretch(-1)
#self.pressing = False
print("MainWindow Loaded")
#self.show()
class MyBar(QWidget):
def __init__(self, parent):
super(MyBar, self).__init__()
self.parent = parent
print(self.parent.width())
self.layout = QHBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.title = QLabel("My Own Bar")
btn_size = 35
self.btn_close = QPushButton("x")
self.btn_close.clicked.connect(self.btn_close_clicked)
self.btn_close.setFixedSize(btn_size,btn_size)
self.btn_close.setStyleSheet("background-color: red;")
self.btn_min = QPushButton("-")
self.btn_min.clicked.connect(self.btn_min_clicked)
self.btn_min.setFixedSize(btn_size, btn_size)
self.btn_min.setStyleSheet("background-color: gray;")
self.btn_max = QPushButton("+")
self.btn_max.clicked.connect(self.btn_max_clicked)
self.btn_max.setFixedSize(btn_size, btn_size)
self.btn_max.setStyleSheet("background-color: gray;")
self.title.setFixedHeight(35)
self.title.setAlignment(Qt.AlignCenter)
self.layout.addWidget(self.title)
self.layout.addWidget(self.btn_min)
self.layout.addWidget(self.btn_max)
self.layout.addWidget(self.btn_close)
self.title.setStyleSheet("background-color: black;color: white;")
self.setLayout(self.layout)
self.start = QPoint(0, 0)
self.pressing = False
print("MyBar Loaded")
def resizeEvent(self, QResizeEvent):
super(MyBar, self).resizeEvent(QResizeEvent)
self.title.setFixedWidth(self.parent.width())
def mousePressEvent(self, event):
self.start = self.mapToGlobal(event.pos())
self.pressing = True
def mouseMoveEvent(self, event):
if self.pressing:
self.end = self.mapToGlobal(event.pos())
self.movement = self.end-self.start
self.parent.setGeometry(self.mapToGlobal(self.movement).x(),
self.mapToGlobal(self.movement).y(),
self.parent.width(),
self.parent.height())
self.start = self.end
def mouseReleaseEvent(self, QMouseEvent):
self.pressing = False
def btn_close_clicked(self):
self.parent.close()
def btn_max_clicked(self):
self.parent.showMaximized()
def btn_min_clicked(self):
self.parent.showMinimized()
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon("icon.png"))
app.setStyleSheet("QWidget {background-color:#424242;border-radius:12px;}")
app.setFont(QFont("Consolas"))
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
The problem is that you have not created or placed a Bar() inside the window. You must also restructure your layout so that the titlebar is displayed at the top and your content at the bottom using a QVBoxLayout.
On the other hand I have improved the original titleBar so that it is not necessary to set the parent directly but instead use the window():
import sys
from PyQt5.QtGui import QFont, QIcon
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QTextEdit, QLabel
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowFlags(Qt.FramelessWindowHint)
hlayout = QHBoxLayout()
self.textArea = QTextEdit("Lorem ipsum...")
hlayout.addWidget(self.textArea)
self.textArea.setStyleSheet("QTextEdit {color:white;background-color:#212121;border-radius:+16px;}")
self.sans = QFont("Segoe UI",20)
self.textArea.setFont(self.sans)
self.btnLayout = QVBoxLayout()
self.btnLayout.addWidget(QPushButton("Open"))
self.btnLayout.addWidget(QPushButton("Setup"))
self.btnLayout.addWidget(QPushButton("Find"))
self.setStyleSheet("QPushButton {max-width:200px;color:#4fc3f7;background-color:#424242;border:2px solid #4fc3f7;border-radius:16px;font-size:35px;font-weight:bold;}" + "QPushButton:hover {color:#212121;background-color:#4fc3f7;}" + "QPushButton:pressed {color:white;background-color:#212121;border-color:white;}")
self.status = QTextEdit()
self.status.insertPlainText("Successfully loaded" + "\nOpen a file...")
self.status.setReadOnly(1)
self.status.setStyleSheet("QTextEdit {color:white;background-color:#212121;border-radius:+16px;font-size:14px;max-width:200px;}")
self.btnLayout.addWidget(self.status)
self.setFixedSize(800, 400)
self.setWindowTitle("Py app")
hlayout.addLayout(self.btnLayout)
custom_titlebar = TitleBar()
lay = QVBoxLayout(self)
lay.addWidget(custom_titlebar)
lay.addLayout(hlayout)
class TitleBar(QWidget):
def __init__(self, parent=None):
super(TitleBar, self).__init__(parent)
self.title = QLabel("My Own Bar")
btn_size = 35
self.btn_close = QPushButton("x")
self.btn_close.clicked.connect(self.btn_close_clicked)
self.btn_close.setFixedSize(btn_size,btn_size)
self.btn_close.setStyleSheet("background-color: red;")
self.btn_min = QPushButton("-")
self.btn_min.clicked.connect(self.btn_min_clicked)
self.btn_min.setFixedSize(btn_size, btn_size)
self.btn_min.setStyleSheet("background-color: gray;")
self.btn_max = QPushButton("+")
self.btn_max.clicked.connect(self.btn_max_clicked)
self.btn_max.setFixedSize(btn_size, btn_size)
self.btn_max.setStyleSheet("background-color: gray;")
self.title.setFixedHeight(35)
self.title.setAlignment(Qt.AlignCenter)
self.title.setStyleSheet("background-color: black;color: white;")
lay = QHBoxLayout(self)
lay.setContentsMargins(0,0,0,0)
lay.addWidget(self.title)
lay.addWidget(self.btn_min)
lay.addWidget(self.btn_max)
lay.addWidget(self.btn_close)
self.pressing = False
self.dragPosition = QPoint()
def resizeEvent(self, QResizeEvent):
super(TitleBar, self).resizeEvent(QResizeEvent)
self.title.setFixedWidth(self.window().width())
def mousePressEvent(self, event):
self.start = event.globalPos()
self.pressing = True
def mouseMoveEvent(self, event):
if self.pressing:
self.end = event.globalPos()
delta = self.end - self.start
self.window().move(self.window().pos() + delta)
self.start = self.end
def mouseReleaseEvent(self, QMouseEvent):
self.pressing = False
def btn_close_clicked(self):
self.window().close()
def btn_max_clicked(self):
self.window().showMaximized()
def btn_min_clicked(self):
self.window().showMinimized()
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("icon.png"))
app.setStyleSheet("QWidget {background-color:#424242;border-radius:12px;}")
app.setFont(QFont("Consolas"))
mw = MainWindow()
mw.show()
sys.exit(app.exec_())

How to update QWidget's content?

There is a QWidget, which is called with the button "Start" in the main widget.
It shows some text, which should be updated every minute during the work of the QWidget.
How can I make this infinity updating within this code?
class ExampleWidget(QWidget):
def __init__(self, parent=None):
super().__init__()
self.setWindowTitle('Example Widget ScrollArea')
self.initUi()
def initUi(self):
area = QScrollArea(self)
area.setWidgetResizable(True)
self.scrollAreaWidgetContents = QLabel(some_text, self)
area.setWidget(self.scrollAreaWidgetContents)
button = QPushButton("Close")
button.clicked.connect(self.goMainWindow)
layoutV = QVBoxLayout()
layoutV.addWidget(area)
layoutV.addWidget(button)
self.setLayout(layoutV)
def goMainWindow(self):
self.hide()
def sizeHint(self):
return QSize(400, 200)
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
start_main_button = QPushButton('Start', self)
start_main_button.move(40, 40)
start_main_button.clicked.connect(self.start)
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('Test')
def start(self):
global some_text
some_text = 'some text'
self.result_widget = ExampleWidget()
self.result_widget.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
One of my tries:
def start(self):
global some_text
some_text = 'some text'
self.result_widget = ExampleWidget()
self.result_widget.show()
i = 0
while True:
i+=1
some_text+=str(i)
self.result_widget = ExampleWidget()
self.result_widget.show()
Forget the global variables because they are considered bad practice, on the other hand in a GUI you should avoid having loops that consume a lot of time, and in your case a while True blocks the GUI. In Qt if you want to do periodic tasks you must use a QTimer:
from PyQt5 import QtCore, QtWidgets
class ExampleWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__()
self.setWindowTitle('Example Widget ScrollArea')
self.initUi()
def initUi(self):
area = QtWidgets.QScrollArea()
area.setWidgetResizable(True)
self.scrollAreaWidgetContents = QtWidgets.QLabel("some_text")
area.setWidget(self.scrollAreaWidgetContents)
button = QtWidgets.QPushButton("Close")
button.clicked.connect(self.hide)
layoutV = QtWidgets.QVBoxLayout(self)
layoutV.addWidget(area)
layoutV.addWidget(button)
def update_text(self, text):
# update the text
self.scrollAreaWidgetContents.setText(text)
def sizeHint(self):
return QtCore.QSize(400, 200)
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
start_main_button = QtWidgets.QPushButton('Start', self)
start_main_button.move(40, 40)
start_main_button.clicked.connect(self.start)
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('Test')
self.result_widget = ExampleWidget()
self.timer = QtCore.QTimer(self, interval=60*1000)
self.timer.timeout.connect(self.on_timeout)
self.counter = 0
self.initial_text = "some_text"
def on_timeout(self):
# this method will be called every 60 * 1000 ms
self.initial_text += str(self.counter)
self.result_widget.update_text(self.initial_text)
self.counter += 1
#QtCore.pyqtSlot()
def start(self):
self.result_widget.show()
# start timer
self.timer.start()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

Updating PyQT label

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

Categories