Table of Contents
正确答案
Home Backend Development Python Tutorial PyQt5: Slot connected to click signal not working

PyQt5: Slot connected to click signal not working

Feb 09, 2024 am 11:27 AM

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')
Copy after login

我的视图类

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'
Copy after login

我的主要内容

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()
Copy after login


正确答案


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

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

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

    controller = Controller(view=view)

    sys.exit(app.exec())
Copy after login

尽管如此,让我告诉您,虽然从概念上来说使用 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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles