发送和接收来自另一个类pyqt的信号

发送和接收来自另一个类pyqt的信号

本文介绍了发送和接收来自另一个类pyqt的信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来接收一个类发送到另一个类的信号.我有2个班级:在我的第一堂课中,我有一个函数可以发出一个名为asignal"的信号在我的第二堂课中,我调用了第一堂课,它发出了一个信号.但我无法将头等信号连接到我的按钮上.我该怎么做?

I am needing a way to receive signals sent by a Class to another class.I have 2 classes:In my first class I have a function that emits a signal called 'asignal'In my second class I call the first class function, and it emits a signal. but I can't connect the first class signal to my pushbutton. How I can do that?

我收到此错误:AttributeError: 'QPushButton' object has no attribute 'asignal'

I get this error: AttributeError: 'QPushButton' object has no attribute 'asignal'

from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtWidgets import *
import sys


class Signals(QObject):
    asignal = pyqtSignal(str)

    def __init__(self):
        super(Signals, self).__init__()
        self.do_something()

    def do_something(self):
        self.asignal.emit('Hi, im a signal')


class Main(QWidget):
    def __init__(self):
        super(Main, self).__init__()
        self.setGeometry(300, 250, 400, 300)
        self.show()
        self.coso()

    def coso(self):
        btn = QPushButton('click me')
        btn.asignal.connect(lambda sig: print("Signal recieved" + sig))
        s = Signals()
        s.do_something()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = Main()
    app.exec_()

我想要一种方法来接收从我的信号"类发射到我的主"类的信号.然后,在我的主类中,将信号连接到 Widget.

I want a way to receive the signal emitted from my 'Signals' class to my 'Main' class. And then, in my main class, connect the signal to a Widget.

推荐答案

QPushButton 不是 Signals 对象,所以这就是您收到错误的原因.

QPushButton is not a Signals object, so thats why you get the error.

s = Signals()
s.asignal.connect(lambda sig: print("Signal recieved" + sig))
s.do_something()

这篇关于发送和接收来自另一个类pyqt的信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:03