PyQt6: Calling worker object method makes program temporarily unresponsive - python-3.x

I'm trying to replicate this with Python and PyQt6. I have been successful in creating a working prototype of it.
The problem:
SequenceMemory.request_round is a PyQt6.QtCore.pyqtSignal that is emitted when the user is to be displayed a new round for the game, be it at the start of the game or after a previous round. However, for some reason, when request_round is emitted, the GUI goes unresponsive for about half a second.
I've pin-pointed the problem to the self.request_round.emit() line in the new_round() method of the SequenceMemory class (after commenting out that line the GUI does not go unresponsive), but I can't seem to figure out why this occurs.
I thought the sleep() function in the CreateSequenceWorker class might be the cause but changing the integer passed to sleep() didn't change how long the GUI went unresponsive so I don't think that's the cause.
import sys
import queue
import random
import itertools
import functools
from time import perf_counter
from PyQt6 import QtWidgets as qtw
from PyQt6 import QtGui as qtg
from PyQt6 import QtCore as qtc
class SequenceMemory(qtw.QMainWindow):
SQUARE_PER_ROW = 3
request_round = qtc.pyqtSignal()
kill_thread = qtc.pyqtSignal()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.sequence_history = []
self.sequence_queue = queue.Queue()
self.main_menu()
def main_menu(self):
start_button = qtw.QPushButton("Start")
start_button.released.connect(self.start)
self.main_widget = self.takeCentralWidget()
self.setCentralWidget(start_button)
self.show()
def start(self):
self.setup_GUI()
self.create_board()
self.setup_thread()
self.start_button = self.takeCentralWidget()
self.setCentralWidget(self.main_widget)
self.new_round()
def setup_GUI(self):
self.main_widget = qtw.QWidget()
self.main_widget.setStyleSheet("background-color: white;")
self.main_widget.setLayout(qtw.QGridLayout())
self.main_widget.layout().setSpacing(0)
self.main_widget.layout().setContentsMargins(5, 5, 5, 10)
def setup_thread(self):
self.create_sequence_worker = CreateSequenceWorker()
self.create_sequence_worker_thread = qtc.QThread()
self.create_sequence_worker.moveToThread(
self.create_sequence_worker_thread
)
self.create_sequence_worker_thread.start()
self.create_sequence_worker.show_block.connect(self.update_board)
self.create_sequence_worker.hide_block.connect(self.update_board)
self.request_round.connect(self.create_sequence_worker.create_sequence)
def create_board(self):
self.buttons = [
tuple(
qtw.QPushButton()
for _ in range(self.SQUARE_PER_ROW)
)
for _ in range(self.SQUARE_PER_ROW)
]
for row, column in itertools.product(
range(self.SQUARE_PER_ROW), repeat=2
):
button = self.buttons[row][column]
button.setStyleSheet(
"""
background-color: rgb(186, 196, 255);
border: 5px solid white;
border-radius: 15px;
"""
)
button.setMinimumHeight(150)
self.main_widget.layout().addWidget(
button, row, column, 1, 1
)
def update_board(self, mode: int, row: int, column: int):
if mode:
button = self.buttons[row][column]
button.setStyleSheet(
"""
background-color: rgb(186, 255, 196);
border: 5px solid white;
border-radius: 15px;
"""
)
else:
button = self.buttons[row][column]
button.setStyleSheet(
"""
background-color: rgb(186, 196, 255);
border: 5px solid white;
border-radius: 15px;
"""
)
def new_round(self):
self.request_round.emit()
def closeEvent(self, a0: qtg.QCloseEvent):
self.kill_thread.emit()
self.create_sequence_worker_thread.quit()
self.main_menu()
class CreateSequenceWorker(qtc.QObject):
queue_ready = qtc.pyqtSignal(queue.Queue)
show_block = qtc.pyqtSignal(int, int, int)
hide_block = qtc.pyqtSignal(int, int, int)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.kill = False
self.sequence_history = []
self.sequence_queue = queue.Queue()
def sleep(self, duration: float):
start_time = perf_counter()
while perf_counter() - start_time < duration:
if self.kill:
return False
return True
def create_sequence(self):
self.sleep(0.5)
for row, column in self.sequence_history:
self.sequence_queue.put((row, column))
self.show_block.emit(1, row, column)
if self.sleep(0.5):
self.hide_block.emit(0, row, column)
else:
return
i = 0
while i < len(self.sequence_history) - self.sequence_queue.qsize() + 1:
row, column = random.randrange(3), random.randrange(3)
if self.sequence_history and (row, column) == self.sequence_history[-1]:
continue
self.sequence_history.append((row, column))
self.sequence_queue.put((row, column))
i+=1
self.show_block.emit(1, row, column)
if self.sleep(0.5):
self.hide_block.emit(0, row, column)
else:
return
self.queue_ready.emit(self.sequence_queue)
def kill_thread_event(self):
self.kill = True
class MainWindow(qtw.QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setMinimumHeight(450)
self.setMinimumWidth(450)
self.setWindowFlags(qtc.Qt.WindowType.FramelessWindowHint)
self.setLayout(qtw.QVBoxLayout())
self.layout().setContentsMargins(0, 0, 0, 0)
self.widget = SequenceMemory()
self.layout().addWidget(self.widget)
self.show()
def closeEvent(self, a0) -> None:
self.widget.close()
return super().closeEvent(a0)
if __name__ == "__main__":
app = qtw.QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec())
Above is as minimal as I could get the program to be, without diverging too far away from the program's structure. The full program (in a single file) can be found here.

Related

QHeaderView going out of viewport

I'm having couple of issues while trying to make a QHeaderView for my QTableView.
I want QHeaderView to be resizable by the user (Qt.ResizeMode.Interactive) while being able to stretch its sections proportionately when the window or QTableView is being resized. I found this problem online, and managed to mostly solve it but there is still some stuttering when the resizing begins and I think there should be a better solution than mine. Currently it's done by using QTimer to stop sections from going out of the viewport. Timer is being updated every millisecond. If the update interval is bigger, sections would go out of viewport and magically teleport back when the timer is updated, so once per millisecond in my case. There's still some stuttering visible if the user is dragging sections out of the viewport by dragging their mouse faster, not so visible when the mouse is slower, but visible none the less.
Every section should be resizable and movable, besides the first two. The first two sections should be immovable and fixed. I managed to make them fixed and they don't seem to have an effect on resizing of the sections, but I have no idea how to make them immovable while all the other sections are movable.
Sections should have text eliding, which I managed to make an item delegate for, but setting it on QHeaderView seems to do absolutely nothing (paint() method doesn't even get called). It's probably because item delegate isn't affecting sections, if so, how can I make a delegate that does affect them?
Here's my current code (it's a bit of a mess, but hopefully you'll get the idea):
import sys
import weakref
from typing import Any, Optional
from PyQt6 import QtWidgets, QtCore, QtGui
from PyQt6.QtCore import pyqtSlot, Qt
from PyQt6.QtGui import QFontMetrics
from PyQt6.QtWidgets import QHeaderView, QStyledItemDelegate, QStyleOptionViewItem
class MyItemDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super().__init__(parent)
def paint(self, painter: QtGui.QPainter, option: QStyleOptionViewItem, index: QtCore.QModelIndex) -> None:
text = index.data(Qt.ItemDataRole.DisplayRole)
# print(text)
if text:
elided_text = QFontMetrics(option.font).elidedText(str(text), Qt.TextElideMode.ElideRight, option.rect.width())
painter.drawText(option.rect, Qt.AlignmentFlag.AlignLeft, elided_text)
class HeaderView(QtWidgets.QHeaderView):
def __init__(self,
orientation: QtCore.Qt.Orientation = Qt.Orientation.Horizontal,
parent: Optional[QtWidgets.QWidget] = None):
super(HeaderView, self).__init__(orientation, parent)
item_delegate = MyItemDelegate(self)
self.setItemDelegate(item_delegate)
self.setMinimumSectionSize(5)
self.setStretchLastSection(True)
self.setCascadingSectionResizes(True)
self.setSectionsMovable(True)
self.fixed_section_indexes = (0, 1)
timer = QtCore.QTimer(self)
timer.setSingleShot(True)
timer.setTimerType(Qt.TimerType.PreciseTimer)
timer.timeout.connect(self._update_sizes)
resize_mode_timer = QtCore.QTimer(self)
resize_mode_timer.setTimerType(Qt.TimerType.PreciseTimer)
resize_mode_timer.setSingleShot(True)
resize_mode_timer.timeout.connect(lambda: self.setSectionResizeMode(QHeaderView.ResizeMode.Interactive))
self._resize_mode_timer = weakref.proxy(resize_mode_timer)
self._timer = weakref.proxy(timer)
self.sectionResized.connect(self._handle_resize)
self.setTextElideMode(Qt.TextElideMode.ElideLeft)
self.setDefaultAlignment(Qt.AlignmentFlag.AlignLeft)
self.proportions = []
self.mouse_pressed = False
def mouseReleaseEvent(self, e: QtGui.QMouseEvent) -> None:
self.mouse_pressed = False
super().mouseReleaseEvent(e)
self.proportions = [self.sectionSize(i) / self.width() for i in range(self.count())]
# print(self.mouse_pressed)
def init_sizes(self):
each = self.width() // self.count()
for i in range(self.count()):
self.resizeSection(self.logicalIndex(i), each)
#pyqtSlot(int, int, int)
def _handle_resize(self, logicalIndex: int, oldSize: int, newSize: int):
self._timer.start(1)
def resizeEvent(self, event: QtGui.QResizeEvent):
super().resizeEvent(event)
width = self.width()
# sizes = [self.sectionSize(self.logicalIndex(i)) for i in range(self.count())]
width_without_fixed = width - sum([self.sectionSize(i) for i in self.fixed_section_indexes])
for i in range(self.count()):
if not self.proportions:
break
if i not in self.fixed_section_indexes:
self.resizeSection(i, int(self.proportions[i] * width_without_fixed))
self._timer.start(1)
#pyqtSlot()
def _update_sizes(self):
width = self.width()
sizes = [self.sectionSize(self.logicalIndex(i)) for i in range(self.count())]
# width_without_fixed = width - sum([self.sectionSize(i) for i in self.fixed_section_indexes])
index = len(sizes) - 1
i = 0
while index >= 0 and sum(sizes) > width:
i += 1
if i > 100:
break
if sizes[index] > 5 and index not in self.fixed_section_indexes: # minimum width (5)
new_width = width - (sum(sizes) - sizes[index])
if new_width < 5:
new_width = 5
sizes[index] = new_width
index -= 1
for j, value in enumerate(sizes):
self.resizeSection(self.logicalIndex(j), value)
if not self.proportions:
self.proportions = [self.sectionSize(i) / width for i in range(self.count())]
class Model(QtCore.QAbstractTableModel):
def __init__(self, parent: Optional[QtWidgets.QWidget] = None) -> None:
super(Model, self).__init__(parent)
self.__headers = ["Column A", "Column B", "Column C", "Column D", "Column E", "Column F", "Column G"]
self.__data = []
for i in range(10):
row = [0, 1, 2, 3, 42222222222, 5, 6, 74444444]
self.__data.append(row)
def rowCount(self, index: Optional[QtCore.QModelIndex] = None) -> int:
return len(self.__data)
def columnCount(self, index: Optional[QtCore.QModelIndex] = None) -> int:
return len(self.__headers)
def headerData(self, section: int, orientation: QtCore.Qt.Orientation,
role: QtCore.Qt.ItemDataRole = Qt.ItemDataRole.DisplayRole) -> Any:
if role == Qt.ItemDataRole.DisplayRole:
if orientation == Qt.Orientation.Horizontal:
return self.__headers[section]
return f"{section}"
return None
def data(self, index: QtCore.QModelIndex,
role: QtCore.Qt.ItemDataRole = Qt.ItemDataRole.DisplayRole) -> Any:
if role in [Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.EditRole]:
return self.__data[index.row()][index.column()]
return None
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
view = QtWidgets.QTableView()
view.resize(600, 600)
header = HeaderView()
view.setHorizontalHeader(header)
model = Model()
view.setModel(model)
header.init_sizes()
view.horizontalHeader().resizeSection(0, 30)
view.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
view.horizontalHeader().resizeSection(1, 30)
view.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)
view.show()
app.exec()

Pyqt5 Notification from scratch

I wanted a module programmed on PyQt5 that would make notifications appear on the right side of the screen, so i found a question here:
PyQt5 notification from QWidget
and i used this code with only a few changes, but the problem is, it creates a new window and does not show the QWidget on screen.
Here is the code
class Message(QWidget):
def __init__(self, title, message, parent=None):
QWidget.__init__(self, parent)
self.setLayout(QGridLayout())
self.titleLabel = QLabel(title, self)
self.titleLabel.setStyleSheet(
"font-family: 'Roboto', sans-serif; font-size: 14px; font-weight: bold; padding: 0;")
self.messageLabel = QLabel(message, self)
self.messageLabel.setStyleSheet(
"font-family: 'Roboto', sans-serif; font-size: 12px; font-weight: normal; padding: 0;")
self.buttonClose = QPushButton(self)
self.buttonClose.setIcon(QIcon("extra/close.png"))
self.buttonClose.setFixedSize(14, 14)
self.layout().addWidget(self.titleLabel, 0, 0)
self.layout().addWidget(self.messageLabel, 1, 0)
self.layout().addWidget(self.buttonClose, 0, 1, 2, 1)
class Notification(QWidget):
signNotifyClose = pyqtSignal(str)
def __init__(self, parent=None):
super(QWidget, self).__init__(parent)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
resolution = QDesktopWidget().screenGeometry(-1)
screenWidth = resolution.width()
screenHeight = resolution.height()
self.nMessages = 0
self.mainLayout = QVBoxLayout(self)
self.move(screenWidth, 0)
def setNotify(self, title, message):
m = Message(title, message, self)
self.mainLayout.addWidget(m)
m.buttonClose.clicked.connect(self.onClicked)
self.nMessages += 1
self.setStyleSheet("background-color: black;")
self.show()
def onClicked(self):
self.mainLayout.removeWidget(self.sender().parent())
self.sender().parent().deleteLater()
self.nMessages -= 1
self.adjustSize()
if self.nMessages == 0:
self.close()
and this is the file importing the previous one:
from notifierP import *
import sys
class Example(QWidget):
counter = 0
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.setLayout(QVBoxLayout())
btn = QPushButton("Send Notify", self)
self.layout().addWidget(btn)
self.notification = Notification()
btn.clicked.connect(self.notify)
def notify(self):
self.counter += 1
print(self.counter)
self.notification.setNotify("Title{}".format(self.counter),
"message{}".format(self.counter))
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
My Question is, why does this happen, and how can i fix it?
How it is on my screen
This all it shows, nothing else.
okay the problem here was that the
self.move()
was moving the widget outside the screen, after i changed its possition to inside the screen it works perfectly.

Change QLCDNumber colour when a specific Value is read using pyqt5

I have a code which reads sensor data and outputs it to a LCD number I am using python3 and pyqt5.
Now What i've been tyring to do with no luck is change the background colour of the LCD number when it reaches a certain value. e.g. when the value falls below 100 the background of the LCD widget is red or an image appears saying too low, if it is between 100-300 it is green and over 300 it goes red again. I hope this makes sense, does anyone know how I can achieve this using pyqt5?
here are the relevant segments of my code for the LCD Number
class Worker(QtCore.QThread):
valueFound = QtCore.pyqtSignal(int, name="valueFound")
...
def run(self):
while self.runFlag:
self.valueFound.emit(self.Pressure_Reading())
...
self.worker = Worker(self)
self.worker.valueFound.connect(self.OnValueFound)
....
def OnValueFound(self, value):
self.ui.lcdNumber.display(value)
Use Qt Style Sheets.
import sys
from random import randint
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QTimer
from ui import Ui_MainWindow
class Form(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.i = 0
self.voltageMin = 180
self.voltageMax = 180
self.ui.lcdNumberCur.display(self.i)
self.ui.lcdNumberCur.setStyleSheet("QLCDNumber { background-color: yellow }")
self.ui.pushButton.clicked.connect(self.startTimer)
self.timer = QTimer(self)
self.timer.setInterval(1000)
self.timer.timeout.connect(self.updateData)
self.show()
def startTimer(self):
if self.ui.pushButton.text() == "Start Timer":
self.timer.start(1000)
self.ui.pushButton.setText("Stop Timer")
else:
self.ui.pushButton.setText("Start Timer")
self.timer.stop()
def updateData(self):
voltage = randint(80, 350) # <--- insert your average voltage here
self.ui.lcdNumberCur.display(voltage)
if voltage > self.voltageMax:
self.voltageMax = voltage
self.ui.lcdNumberMax.display(self.voltageMax)
if self.voltageMax > 300:
self.ui.lcdNumberMax.setStyleSheet("""QLCDNumber {
background-color: red;
color: white; }""")
else:
self.ui.lcdNumberMax.setStyleSheet("""QLCDNumber
{ background-color: green;
color: yellow;
}""")
elif voltage < self.voltageMin:
self.voltageMin = voltage
self.ui.lcdNumberMin.display(self.voltageMin)
if self.voltageMin < 90:
self.ui.lcdNumberMin.setStyleSheet("""QLCDNumber {
background-color: red;
color: white; }""")
else:
self.ui.lcdNumberMin.setStyleSheet("""QLCDNumber
{ background-color: green;
color: yellow;
}""")
if __name__ == '__main__':
app = QApplication(sys.argv)
frm = Form()
sys.exit(app.exec_())

PyQt - can I add a QWidget in paintEvent?

I am using PyQt to make an application that, amongst other things, shows information in a simple graphical diagram.
I have done this as a QWidget and reimplemented the paintEvent method to do the drawing. A small and very cut-down example is show below.
from PyQt4.QtCore import *
from PyQt4.QtGui import * # sloppy, I know, but done for speed! :-)
class Example(QMainWindow):
def __init__(self,parent=None):
super(Example,self).__init__(parent)
self.init_ui()
def init_ui(self):
base=QWidget()
layout=QVBoxLayout(base)
self.diagram=Diagram()
layout.addWidget(self.diagram)
self.setCentralWidget(base)
class Diagram(QWidget):
def __init__(self,parent=None):
super(Diagram,self).__init__(parent)
self.width=360
self.height=120
self.leftMargin=10
self.topMargin=10
def paintEvent(self,event=None):
painter=QPainter(self)
painter.setWindow(self.leftMargin,self.topMargin,self.width,self.height)
self.drawConnection(painter, 40, 25, 40, 90)
self.drawConnection(painter, 40, 90, 40, 110)
self.drawConnection(painter, 40, 110, 200, 100)
self.drawItem(painter, 40, 40)
self.drawItem(painter, 40, 90)
self.drawState(painter,200,100)
def drawConnection(self,painter,x0,y0,x1,y1):
pen=QPen()
pen.setWidth(4)
pen.setColor(QColor(50,50,200))
painter.setPen(pen)
painter.drawLine(x0,y0,x1,y1)
def drawItem(self,painter,x,y):
w=40
h=30
r=QRectF(x-(w/2),y-(h/2),w,h)
painter.drawRoundedRect(r,5.0,5.0)
grad=QLinearGradient(QPointF(15.0,20.0),QPointF(30.0,30.0))
pen=QPen()
pen.setWidth(2)
pen.setColor(QColor(10,10,10))
painter.setPen(pen)
brush=QBrush(QColor(0,200,10))
painter.setBrush(brush)
painter.drawRoundedRect(r,5.0,5.0)
def drawState(self,painter,x,y):
w=80
h=60
r=QRectF(x-(w/2),y-(h/2),w,h)
pen=QPen()
pen.setWidth(2)
pen.setColor(QColor(255,10,10))
painter.setPen(pen)
brush=QBrush(QColor(200,200,10))
painter.setBrush(brush)
painter.drawPie(r,5040,1440)
if __name__=='__main__':
app=QApplication(sys.argv)
example=Example()
example.show()
app.exec_()
Is it possible to add a QWidget instead of calling drawItem?
For example, a suitably styled QPushButton could go in place of the rounded rectangles.
Alternatively, what is the best way to go about creating a display that contains both widgets and painted items?
I have written a rounded child widget example, using the QSS.
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
ROUNDED_STYLE_SHEET = """QPushButton {
background-color: red;
border-style: outset;
border-width: 2px;
border-radius: 10px;
border-color: beige;
font: bold 14px;
min-width: 10em;
padding: 6px;
}
"""
class MyWidget(QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self.mChildWidget = QPushButton(self)
self.resize(600, 400)
self.mChildWidget.resize(120, 80)
self.mChildWidget.move(300, 200)
self.mChildWidget.setStyleSheet(ROUNDED_STYLE_SHEET)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWidget()
w.show()
app.exec_()

How to shift position of radio button and reverse radio button function when unchecking it?

I would like to ask 2 questions about my code. First, how do I shift the position of my radio button into the position that I want (I wrote it in the code)? And how do I reverse my LCD screen after unchecking it? Right now, it shows '02' when checked but I want to reverse the process when I uncheck it. Any solution?
class MyRadioButton(QtGui.QRadioButton):
def __init__(self):
super(MyRadioButton, self).__init__()
self.value = None
def SetValue(self, val):
self.value = val
def GetValue(self):
return self.value
class UserTool(QtGui.QDialog):
def __init__(self, parent = None):
super(UserTool, self).__init__()
self.layout = QtGui.QVBoxLayout(self)
self.setup(self)
def setup(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
self.resize(688, 677)
self.lcdNumber = QtGui.QLCDNumber(Dialog)
self.lcdNumber.setGeometry(QtCore.QRect(590, 10, 71, 23))
self.lcdNumber.setFrameShadow(QtGui.QFrame.Raised)
self.lcdNumber.setObjectName(_fromUtf8("lcdNumber"))
self.lcdNumber.setStyleSheet("* {background-color: black; color: white;}")
self.lcdNumber.display("00")
self.radioButton_8 = MyRadioButton()
self.radioButton_8.setText("A1")
self.radioButton_8.SetValue("02")
self.radioButton_8.toggled.connect(self.showValueFromRadioButtonToLCDNumber)
self.layout.addWidget(self.radioButton_8)
#self.radioButton_8 = QtGui.QRadioButton(Dialog)
self.radioButton_8.setGeometry(QtCore.QRect(460, 10, 82, 17))
self.radioButton_8.setChecked(False)
self.radioButton_8.setAutoExclusive(False)
self.radioButton_8.setObjectName(_fromUtf8("radioButton_8"))
def retranslateUi(self, Dialog):
self.radioButton_8.setText(_translate("Dialog", "A1", None))
def showValueFromRadioButtonToLCDNumber(self):
value = self.radioButton_8.GetValue()
if self.radioButton_8.isChecked():
self.lcdNumber.display(value)
Here is working example. In order to show previous value you need mechanism to cash that value before it is changed. To shift radioButton I use addSpacing()
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
class MyRadioButton(QtGui.QRadioButton):
def __init__(self):
super(MyRadioButton, self).__init__()
self.value = None
def SetValue(self, val):
self.value = val
def GetValue(self):
return self.value
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
self.layout = QtGui.QVBoxLayout(self)
self.radioButton = MyRadioButton()
self.radioButton.setText("some text")
self.radioButton.SetValue("02")
self.radioButton.toggled.connect(self.showValueFromRadioButtonToLCDNumber)
self.lcdNumber = QtGui.QLCDNumber()
self.lcdNumber.display("-2")# previous value
self.layoutHorizontal = QtGui.QHBoxLayout(self)
self.layoutHorizontal.addSpacing(20)# add space before radioButton
self.layoutHorizontal.addWidget(self.radioButton)
self.layout.addLayout(self.layoutHorizontal)
self.layout.addWidget(self.lcdNumber)
self.previousValue = ""
def showValueFromRadioButtonToLCDNumber(self):
value = self.radioButton.GetValue()
if self.radioButton.isChecked():
self.previousValue = self.lcdNumber.value()# save previous value before it is changed
self.lcdNumber.display(value)
else:
self.lcdNumber.display(self.previousValue)

Resources