PyQt program connection between singal and function is not working

Viewed 44

In this very simple PyQt based Python program start button does not work, it seems that there is no connection between the start button and _calculateResult method. I think something in _connectSignals() method is wrong, but I cannot find it. Do you have any idea about it? Thanks.

import sys

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QLineEdit, QPushButton, QHBoxLayout

class TimerUi(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Basic Timer')
        self.setFixedSize(235, 235)
        self.generalLayout = QHBoxLayout()
        self._centralWidget = QWidget(self)
        self.setCentralWidget(self._centralWidget)
        self._centralWidget.setLayout(self.generalLayout)
        self._createDisplayAndButtons()

    def _createDisplayAndButtons(self):
        self.display = QLineEdit()
        self.display.setFixedHeight(35)
        self.generalLayout.addWidget(self.display)

        self.buttons = {}
        self.buttons['start'] = QPushButton('Start')
        self.buttons['start'].setFixedSize(40, 40)
        self.generalLayout.addWidget(self.buttons['start'])

    def setDisplayText(self, text):
        self.display.setText(text)
        self.display.setFocus()

class PyCalcCtrl:
    def __init__(self, view):
        self._view = view
        self._connectSignals()

    def _calculateResult(self):
        self._view.setDisplayText('Time is 17:13')

    def _connectSignals(self):
        self._view.buttons['start'].clicked.connect(self._calculateResult)

def main():
    basic_timer = QApplication(sys.argv)
    view = TimerUi()
    view.show()
    PyCalcCtrl(view=view)
    sys.exit(basic_timer.exec_())


if __name__ == '__main__':
    main()
1 Answers

By creating the PyCalcCtrl object and not assigning it to a variable then the GC removed it. The solution is to assign that object to a variable:

def main():
    basic_timer = QApplication(sys.argv)
    view = TimerUi()
    view.show()
    ctrl = PyCalcCtrl(view=view)
    sys.exit(basic_timer.exec_())
Related