PyQt program connection between singal and function is not working

♀尐吖头ヾ 提交于 2021-02-05 06:42:04

问题


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:


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


来源:https://stackoverflow.com/questions/60840579/pyqt-program-connection-between-singal-and-function-is-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!