Reputation: 6147
The image attached shows the custom widget i'm creating for a larger project. The first widget consists of
I then take this custom widget and create two instances of it in my new second widget. I want to change the label of each instance to something unique. The goal being to have one widget labeled 'Teams' and the other 'Members'. How do i make it possible for me to change the label of each instance of the initial custom widget?
Current UI
Target UI
the goods...
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
In this example, we create a custom widget.
authors:
website: JokerMartini.com
"""
import sys
from PySide import QtGui, QtCore
class NameListWidget(QtGui.QWidget):
def __init__(self):
super(NameListWidget, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Input List')
# widgets
self.listLabel = QtGui.QLabel("Label")
self.nameInput = QtGui.QLineEdit()
self.nameList = QtGui.QListWidget()
# layout
self.mainLayout = QtGui.QVBoxLayout(self)
self.mainLayout.setContentsMargins(0,0,0,0)
self.mainLayout.addWidget(self.listLabel)
self.mainLayout.addWidget(self.nameInput)
self.mainLayout.addWidget(self.nameList)
self.show()
class FactionWidget(QtGui.QWidget):
def __init__(self):
super(FactionWidget, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Teams')
# widgets
self.sportsListWidget = NameListWidget()
self.memebersListWidget = NameListWidget()
# layout
self.mainLayout = QtGui.QHBoxLayout(self)
self.mainLayout.setSpacing(10)
self.mainLayout.setContentsMargins(10,10,10,10)
self.mainLayout.addWidget(self.sportsListWidget)
self.mainLayout.addWidget(self.memebersListWidget)
self.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = FactionWidget()
sys.exit(app.exec_())
Upvotes: 0
Views: 363
Reputation: 4777
You can either set it directly from your instance:
ex.sportsListWidget.listLabel.setText('Teams')
ex.memebersListWidget.listLabel.setText('Members')
Or your NameListWidget
's constructor method can include a string parameter that will set the label on its creation. (This should be the better approach)
class NameListWidget(QtGui.QWidget):
def __init__(self, title):
super(NameListWidget, self).__init__()
self.initUI()
self.listLabel.setText(title)
Then when you're adding them in FactionWidget
:
# widgets
self.sportsListWidget = NameListWidget('Teams')
self.memebersListWidget = NameListWidget('Members')
Is this what you're after?
Upvotes: 1