-1

How to Convert 'Str' into a 'Qwidget'? (Initialize my dictionary outside the class method)

...

        dict_link = {'11': 'self.container11', '12': 'self.container12', '13': 'self.container13',
                     '14': 'self.fcontainer14'}
    
        kj = dict_link.get('11')
        
        print(kj)
        print('Kj Type :',type(kj))
    
       
        self.stackitem_menubar2_right.setCurrentWidget(kj)

getting the following error:

TypeError: setCurrentWidget(self, QWidget): argument 1 has unexpected type 'str'
Bala
  • 648
  • 5
  • 15
  • Which QWidget do you want to convert the string `'self.container11'` to? – mkrieger1 Sep 04 '22 at 23:41
  • self.container11 = QWidget() self.container11_box = QVBoxLayout(self.container11) self.container11_box.addWidget(self.lbl_underconstruction). Load this item into stackitem, through dictionery option @ mkrieger – Bala Sep 04 '22 at 23:47
  • 1
    Remove `"self."` from all the values in the dict. Then you can do: `widget = getattr(self, kj); self.stackitem_menubar2_right.setCurrentWidget(widget)`. But there are probably ways to restructure your code that would avoid this kind of indirection. – ekhumoro Sep 05 '22 at 09:51

2 Answers2

0

I guess you have a class with self.container11 = SomeWidget(). Technically you access the class attributes by their names (with str) like that:

from PyQt5.QtWidgets import QWidget, QStackedWidget, QApplication


class MyClass:
    def __init__(self):
        self.app = QApplication([])
        self.container11 = QWidget()
        self.container12 = QWidget()
        self.container13 = QWidget()
        self.fcontainer14 = QWidget()
        self.stackitem_menubar2_right = QStackedWidget()
        self.stackitem_menubar2_right.addWidget(self.container11)


dict_link = {
    "11": "container11",
    "12": "container12",
    "13": "container13",
    "14": "fcontainer14",
}
my_class = MyClass()
kj = getattr(my_class, dict_link.get('11'))
print(kj)
print('Kj Type :', type(kj))
my_class.stackitem_menubar2_right.setCurrentWidget(kj)

u1234x1234
  • 2,062
  • 1
  • 1
  • 8
0

This is because you mix the name with the object. You have to create a widget first and then you can name it according to you list

accpert.com
  • 109
  • 11