简体   繁体   中英

PySide edit widget from another class

I'm having trouble with a program that I'm writing. As its going to be quite large, I want to separate the layouts and signals, etc into separate classes/modules to make things easier to read. I would like to be able to edit the layout widgets from another class. Is this possible, or am I trying to do something that is not possible? I've included an example below, in case my explanation is not clear

class Layout:
  def __init__(self):
    self.callback = CallBack()

  def Gui(self):
    ''' 
    some layout with a listwidget that affects another listwidget depending on choice for example
    '''
    self.list1 = QtGui.QListWidget()
    self.list1.addItems(['chocolate', 'candy', 'pop'])

    self.list1.itemClicked.connect(self.callback.ButtonCallback)

    self.list2 = QtGui.QListWidget()

class CallBack(Layout):
  def __init__(self)
    super(CallBack, self).__init__()

  def ButtonCallback(self, button_signal):
    '''
    do get options for self.list2 depending on chosen item
    '''

    new_items = ['item1', 'item2', 'item3']
    Layout.list2.addItems(new_items)

I realize that the last line of the code is probably wrong but that is the part that I'm struggling with.

Many thanks for any help.

You can certainly have other objects answer your signals for you as long as they conform to QObject. In the example code that you have written, I would create the CallBack object as a subclass of QObject and retain a relationship to the Layout that owns it so that it can access the Layout object's attributes.

class Layout:
    def __init__(self):
        self.callback = CallBack(self)

    def Gui(self):
    ''' 
    some layout with a listwidget that affects another listwidget depending on choice for example
    '''
    self.list1 = QtGui.QListWidget()
    self.list1.addItems(['chocolate', 'candy', 'pop'])

    self.list1.itemClicked.connect(self.callback.ButtonCallback)

    self.list2 = QtGui.QListWidget()

class CallBack(QtCore.QObject):
    def __init__(self, parent)
        super(CallBack, self).__init__()
        self.parent = parent

    def ButtonCallback(self, button_signal):
    '''
    do get options for self.parent.list2 depending on chosen item
    '''

    new_items = ['item1', 'item2', 'item3']
    self.parent.list2.addItems(new_items)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM