Home > database >  How to create a new object in the .connect function with pyqt?
How to create a new object in the .connect function with pyqt?

Time:11-28

I want to create a new object of the Class Lamp with the name of the clicked item.

self.listWidget_lamps.clicked.connect(Hue = Lamp(name_item))

Since this is not working, I would like to now what the right way looks like and how I need to inherit the Lamp class to the class Ui_MainWindow(object):.

Here is my code (issue line 52): https://pastebin.com/rjg96kuJ

Here is the init of the class Lamps:

class Lamp:
    """Class to control phillips hue lamps/groups"""

    def __init__(self, name: str):
        self.name = name
        with open("data.json", "r") as self.file:
            self.data = json.load(self.file)
        self.brightness = self.data["lamps"][self.name]["brightness"]
        self.xy = self.data["lamps"][self.name]["color"]

CodePudding user response:

The input into ...cliked.connect() has to be a function - something that can be called with a pair of brackets. So Hue = ... will not work. Instead, use a lambda function or a function you have defined. Also note that to get the name of an item you should use ...itemClicked.connect() not ...clicked.connect() which passes the item clicked as a parameter to the function. This is (I believe) the shortest way of doing it, although very unreadable and not recommended:

self.listWidget_lamps.itemClicked.connect(lambda item: globals().update({"Hue": Lamp(item.text())}))

This is the recommended way:

Hue = None
def new_lamp(item):
    global Hue
    Hue = Lamp(item.text())
self.listWidget_lamps.itemClicked.connect(new_lamp)
  • Related