Skip to content

Instantly share code, notes, and snippets.

@ishikawash
Created June 26, 2021 02:59
Show Gist options
  • Save ishikawash/7ffcebd43aa91bbee1a23f002f5b78d4 to your computer and use it in GitHub Desktop.
Save ishikawash/7ffcebd43aa91bbee1a23f002f5b78d4 to your computer and use it in GitHub Desktop.
Fibonacci number calculation with Python generator and QTimer.
import sys
import enum
from PySide2 import QtCore
from PySide2.QtWidgets import QApplication, QWidget, QMainWindow, QLabel, QPushButton, QVBoxLayout
def fibo():
a = 0
b = 1
while True:
c = a + b
yield c
a = b
b = c
class TimerToggleState(enum.Enum):
Start = 0
Stop = 1
def main():
app = QApplication(sys.argv)
window = QMainWindow()
label = QLabel("0")
label.setAlignment(QtCore.Qt.AlignRight)
label.setStyleSheet("font-size: 32px; font: bold")
button = QPushButton(TimerToggleState.Start.name)
button.setCheckable(True)
timer = QtCore.QTimer(window)
def update_number():
for x in fibo():
label.setText(str(x))
yield
def task(update):
g = update()
@QtCore.Slot()
def next():
g.__next__()
return next
timer.timeout.connect(task(update_number))
@QtCore.Slot(bool)
def toggle_timer(checked):
if checked:
timer.start(500)
button.setText(TimerToggleState.Stop.name)
else:
timer.stop()
button.setText(TimerToggleState.Start.name)
button.clicked.connect(toggle_timer)
layout = QVBoxLayout()
layout.addWidget(label)
layout.addWidget(button)
content = QWidget()
content.setLayout(layout)
window.setCentralWidget(content)
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment