nghiep
nghiep

Reputation: 3

cannot be associated with QComboBox

button of class Main don't connect with class Qcombobox of Signals

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


class Signals(QWidget):
    asignal = pyqtSignal(str)
    def __init__(self):
        super(Signals, self).__init__()
        self.setGeometry(300, 250, 400, 300)
        self.ii()
        self.show()

    def ii(self):
        vbox = QVBoxLayout()

        self.combo = QComboBox()
        self.combo.addItem("Python")
        self.combo.addItem("Java")
        self.combo.addItem("C++")
        self.combo.addItem("C#")
        self.combo.addItem("Ruby")

        self.buttom = QPushButton("Click")
        self.buttom.clicked.connect(self.windown2)
        vbox.addWidget(self.combo)
        vbox.addWidget(self.buttom)
        self.setLayout(vbox)
    def do_something(self):
        self.asignal.emit(self.combo.currentText())

    def windown2(self):
        self.ggpp = Main()  
        self.ggpp.show()


class Main(QWidget):

    def __init__(self):
        super(Main, self).__init__()
        self.setGeometry(500,150, 600, 300)
        vbox1 = QVBoxLayout()

        self.buttom1 = QPushButton("Click")
        self.buttom1.clicked.connect(self.coso1)
    
        vbox1.addWidget(self.buttom1)
        self.setLayout(vbox1)

    def coso1(self):
        s = Signals()
        s.asignal.connect(lambda sig: print("self.combo.currentText()>>>>>" + sig))
        s.do_something()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    nals = Signals()
    nals.show()
    sys.exit(app.exec())

enter image description here

enter image description here

Upvotes: 0

Views: 56

Answers (1)

musicamante
musicamante

Reputation: 48374

What you see happens because you're not using the existing instance of Signals, but you're creating a new one each time the button is clicked.

In your case, you could add a reference to the instance as an argument when you create the new window, so that you can correctly connect to its signal.

class Signals(QWidget):
    # ...
    def windown2(self):
        self.ggpp = Main(self)
        self.ggpp.show()

class Main(QWidget):
    def __init__(self, signals):
        super(Main, self).__init__()

        self.signals = signals
        self.signals.asignal.connect(self.coso1)

        self.setGeometry(500,150, 600, 300)
        vbox1 = QVBoxLayout()

        self.buttom1 = QPushButton("Click")
        self.buttom1.clicked.connect(self.signals.do_something)
    
        vbox1.addWidget(self.buttom1)
        self.setLayout(vbox1)

    def coso1(self, sig):
        print("self.combo.currentText()>>>>>" + sig)

Upvotes: 1

Related Questions