search
HomeBackend DevelopmentPython TutorialPyQt5: Slot connected to click signal not working

PyQt5: Slot connected to click signal not working

问题内容

首先,对不起我的英语。我的母语是西班牙语。 所以,我正在做这个小项目来学习python。我正在学习如何使用 pyqt5 做 ui。这个应用程序很简单,它有三个输入、一个按钮和一个输出。 我在此应用程序中使用 mvc 软件模式,并且我的视图、模型和控制器位于单独的文件中。

问题: 在控制器类中,我将唯一的按钮连接到名为 (_calculate) 的插槽。当我运行应用程序并按下该按钮时,终端应该打印一条文本,以便我可以查看它是否正常工作。终端没有向我显示任何内容。 尝试不同类型的事情后,我发现如果我在视图类中执行相同的绑定,则会执行 _calculate 。我做了一个关于使用 pyqt5 的计算器的教程。本教程中的计算器使用 mvc 工作得很好,所以我用它来查明我是否忘记或错过了某些内容,但没有出现任何明显的情况。

我的控制器类

class controller:
def __init__(self, view):
    self._view = view
    self._connectsignals()


def _connectsignals(self):
    self._view.button.clicked.connect(self._calculate)


def _calculate(self):
    print('trying to calculate')

我的视图类

from pyqt5.qtwidgets import qmainwindow
from pyqt5.qtwidgets import qvboxlayout
from pyqt5.qtwidgets import qhboxlayout
from pyqt5.qtwidgets import qwidget
from pyqt5.qtwidgets import qlabel
from pyqt5.qtwidgets import qlineedit
from pyqt5.qtwidgets import qspaceritem
from pyqt5.qtwidgets import qsizepolicy
from pyqt5.qtwidgets import qpushbutton
from pyqt5.qtwidgets import textedit

from pyqt5.qtgui import qpixmap

from pyqt5.qtcore import qt
from toolcontroller import controller

class userinterface(qmainwindow):
  def __init__(self):
    super().__init__()

    self.setwindowtitle('bdo tool')
    self.setfixedsize(450, 300)
    self._centralwidget = qwidget(self)
    self.setcentralwidget(self._centralwidget)
    self._createwindowskeleton()


  def _createwindowskeleton(self):
    # vertical container who contains all the program widget
    self._generallayout = qvboxlayout()
    self._centralwidget.setlayout(self._generallayout)
    self._generallayout.setalignment(qt.aligncenter)

    self._generallayout.addlayout(self._createfirstrow())
    self._generallayout.addlayout(self._createbutton())
    self._generallayout.addwidget(self._createareatext())


  def _createfirstrow(self):
    hlayout = qhboxlayout()
    spacer = qspaceritem(20, 20, hpolicy=qsizepolicy.expanding)
    self._inputboxes = {
            self.input_base_fail: (qpixmap(self.img_base_fails), qlineedit()),
            self.input_target_fail: (qpixmap(self.img_target_fail), qlineedit()),
            self.input_stack_amount: (qpixmap(self.img_stack_amount), qlineedit()),
        }
    keys = list(self._inputboxes.keys())

    for key, value in self._inputboxes.items():
        pixmap, editline = value
        label = qlabel()

        label.setpixmap(pixmap)
        editline.setfixedwidth(40)
        editline.setalignment(qt.alignright)

        hlayout.addwidget(label)
        hlayout.addwidget(editline)

        if key != keys[-1]:
            hlayout.addspaceritem(spacer)

    return hlayout


  def _createbutton(self):
    self.button = qpushbutton('calculate')
    spacer = qspaceritem(20, 20, hpolicy=qsizepolicy.expanding)
    hlayout = qhboxlayout()

    hlayout.addspaceritem(spacer)
    hlayout.addwidget(self.button)
    hlayout.addspaceritem(spacer)

    return hlayout


  def _createareatext(self):
    self._infodisplay = qtextedit()
    self._infodisplay.setenabled(false)

    return self._infodisplay

  input_base_fail = 1
  input_target_fail = 2
  input_stack_amount = 3
  img_base_fails = 'img\\user25x25.png'
  img_target_fail = 'img\\target25x25.png'
  img_stack_amount = 'img\\stack25x25.png'

我的主要内容

import sys

from PyQt5.QtWidgets import QApplication

from ToolView import UserInterface
from ToolController import Controller


def main():
    app = QApplication(sys.argv)
    view = UserInterface()
    view.show()

    Controller(view=view)

    sys.exit(app.exec())


if __name__ == '__main__':
    main()

正确答案


问题是您没有为控制器实例创建持久对象,因此该实例随后会立即被垃圾收集,因为它没有在其他任何地方引用。

只要存在对实例的引用,它就会按预期工作。
在这种情况下,一个局部变量就足够了,因为 app.exec() 将阻止 main 内的进一步处理,确保实例将存在直到它存在。

def main():
    app = QApplication(sys.argv)
    view = UserInterface()
    view.show()

    controller = Controller(view=view)

    sys.exit(app.exec())

尽管如此,让我告诉您,虽然从概念上来说使用 mvc 通常是一个好主意,但您应该谨慎使用它,不要“夸大”模式,并且只有在它确实有助于开发时才使用它。

我想指出其中一个mvc 的缺点

我知道您的示例是一个简单且概念性的示例,但就其用途而言,它确实是一个过于复杂的示例。例如:

  • 您似乎没有使用模型,或者至少您似乎不需要完整的 mvc 模式来做到这一点(只要有实际优势,就应该选择 mvc)这样做,而不是“因为你应该使用它”);
  • 使用 mvc 模式并不一定意味着您必须使用 3 个类(和 3 个单独的文件),这也可能会降低代码的可导航性; mvc 主要是关于程序逻辑中这三个元素的划分方式:qt(大多数提供 ui 元素的框架)已经对此有所帮助,因为它提供了除了显示自身之外几乎不执行任何操作的 ui 元素,以及允许交互的其他元素与它们(文件访问、网络接口和实际模型);
  • 过度使用函数来创建 ui 通常是一个坏主意,因为它使事情变得比实际情况复杂得多,最重要的是从可读性的角度来看:虽然使用单独的函数可能有助于为了保持代码“更整洁”,还创建了函数以实现可重用性,并且在 userinterface 类中,有 4 个函数肯定只会使用一次。

The above is the detailed content of PyQt5: Slot connected to click signal not working. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.