populate python qt widget with items from class - python

I've written a script here in python which consists of a class I made called 'Profile'. Each profile has a 'Name' and list of 'Plugin Names'
I need help getting the list to populate the Ui. When the ui is initiated I want the dropdownlist to be populated with the 'Names' of each profile. Then as the 'Profile' is selected, the listbox be populate with the appropriate plugin names. I've commented out the profiles as I wasn't sure how to properly get them working.
Hope that is clear explaining.
import sys, os
from PyQt4 import QtCore, QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
class Profile(object):
def __init__(self, name, plugins):
self.name = name
self.plugins = plugins
def initUI(self):
# UI CONTORLS
uiProfiles = QtGui.QComboBox(self)
uiPluginList = QtGui.QListWidget(self)
uiLaunch = QtGui.QPushButton("Launch")
# STYLING
uiLaunch.setToolTip('This is a <b>QPushButton</b> widget')
uiLaunch.resize(uiLaunch.sizeHint())
uiLaunch.setMinimumHeight(30)
# UI LAYOUT
grid = QtGui.QGridLayout()
grid.setSpacing(10)
grid.addWidget(uiProfiles, 1, 0)
grid.addWidget(uiPluginList, 2, 0)
grid.addWidget(uiLaunch, 3, 0)
self.setLayout(grid)
self.setGeometry(300, 500, 600, 200)
self.setWindowTitle('3ds Max Launcher')
self.resize(400,150)
self.show()
# profiles = [
# Profile(name="3ds Max Workstation", plugins=["FumeFX", "Afterworks", "Multiscatter"]),
# Profile(name="3ds Max All Plugins", plugins=["FumeFX"]),
# Profile(name="3ds Max Lite", plugins=["default 3ds max"]),
# ]
# for p in profiles:
# uiProfiles.addItem(p.name)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

You had a few problems. Your MainWindow never got shown. You were defining the Profile class inside your Example class (instead of on it's own). You also had no event function that did something when the user changed the profile list.
I made put the profile names into a QStringListModel. This means that any changes to the names in the model will automatically update the widget. You don't have to do it this way, but it's easier in larger projects and not really any harder to do.
I also connected a function to the event that occurs when the value of the combo box is changed. You will need to make another event function and connect it to a launch button event as well.
import sys, os
from PyQt4 import QtCore, QtGui
class Profile(object):
def __init__(self, name, plugins):
self.name = name
self.plugins = plugins
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.profiles = [Profile(name="3ds Max Workstation", plugins=["FumeFX", "Afterworks", "Multiscatter"]),
Profile(name="3ds Max All Plugins", plugins=["FumeFX"]),
Profile(name="3ds Max Lite", plugins=["default 3ds max"])]
profile_names = [p.name for p in self.profiles]
# make a model to store the profiles data in
# changes to data will automatically appear in the widget
self.uiProfilesModel = QtGui.QStringListModel()
self.uiProfilesModel.setStringList(profile_names)
# UI CONTORLS
self.uiProfiles = QtGui.QComboBox(self)
self.uiPluginList = QtGui.QListWidget(self)
self.uiLaunch = QtGui.QPushButton("Launch")
# associate the model to the widget
self.uiProfiles.setModel(self.uiProfilesModel)
# connect signals
self.uiProfiles.currentIndexChanged.connect(self.on_select_profile)
# STYLING
self.uiLaunch.setToolTip('This is a <b>QPushButton</b> widget')
self.uiLaunch.resize(self.uiLaunch.sizeHint())
self.uiLaunch.setMinimumHeight(30)
# UI LAYOUT
grid = QtGui.QGridLayout()
grid.setSpacing(10)
grid.addWidget(self.uiProfiles, 1, 0)
grid.addWidget(self.uiPluginList, 2, 0)
grid.addWidget(self.uiLaunch, 3, 0)
self.setLayout(grid)
self.setGeometry(300, 500, 600, 200)
self.setWindowTitle('3ds Max Launcher')
self.resize(400,150)
self.show()
# run once to fill in list
self.on_select_profile(0)
def on_select_profile(self, index):
# clear list
self.uiPluginList.clear()
# populate list
for plugin in self.profiles[index].plugins:
self.uiPluginList.addItem(plugin)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())

Related

PyQt5 removing button

In the list_widget I have added a add button I also want to add a remove button which asks which item you wants to remove and remove the chosen item. I was trying it to do but I didn't had any idea to do so .Also, please explain the solution I am a beginner with pyqt5 or I'd like to say absolute beginner.
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication,QMainWindow,
QListWidget, QListWidgetItem
import sys
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.x = 200
self.y = 200
self.width = 500
self.length = 500
self.setGeometry(self.x, self.y, self.width,
self.length)
self.setWindowTitle("Stock managment")
self.iniTUI()
def iniTUI(self):
# buttons
self.b1 = QtWidgets.QPushButton(self)
self.b1.setText("+")
self.b1.move(450, 100)
self.b1.resize(50, 25)
self.b1.clicked.connect(self.take_inputs)
# This is the button I want to define.
self.btn_minus = QtWidgets.QPushButton(self)
self.btn_minus.setText("-")
self.btn_minus.move(0, 100)
self.btn_minus.resize(50, 25)
# list
self.list_widget = QListWidget(self)
self.list_widget.setGeometry(120, 100, 250, 300)
self.item1 = QListWidgetItem("A")
self.item2 = QListWidgetItem("B")
self.item3 = QListWidgetItem("C")
self.list_widget.addItem(self.item1)
self.list_widget.addItem(self.item2)
self.list_widget.addItem(self.item3)
self.list_widget.setCurrentItem(self.item2)
def take_inputs(self):
self.name, self.done1 =
QtWidgets.QInputDialog.getText(
self, 'Add Item to List', 'Enter The Item you want
in
the list:')
self.roll, self.done2 = QtWidgets.QInputDialog.getInt(
self, f'Quantity of {str(self.name)}', f'Enter
Quantity of {str(self.name)}:')
if self.done1 and self.done2:
self.item4 = QListWidgetItem(f"{str(self.name)}
Quantity{self.roll}")
self.list_widget.addItem(self.item4)
self.list_widget.setCurrentItem(self.item4)
def clicked(self):
self.label.setText("You clicked the button")
self.update()
def update(self):
self.label.adjustSize()
def clicked():
print("meow")
def window():
apk = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(apk.exec_())
window()
The core issue here is the lack of separation of the view and the data. This makes it very hard to reason about how to work with graphical elements. You will almost certainly want to follow the Model View Controller design paradigm https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
which offers a systematic way to handle this separation.
Once you do so, it immediately becomes very straight forward how to proceed with the question: You essentially just have a list, and you either want to add a thing to this list, or remove one based on a selection.
I include an example here which happens to use the built-in classes QStringListModel and QListView in Qt5, but it is simple to write your own more specialized widgets and models. They all just use a simple signal to emit to the view that it needs to refresh the active information.
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class StuffViewer(QMainWindow):
def __init__(self, model):
super().__init__()
self.setWindowTitle("Stock managment")
# 1: Use layouts.
hbox = QHBoxLayout()
widget = QWidget()
widget.setLayout(hbox)
self.setCentralWidget(widget)
# 2: Don't needlessly store things in "self"
vbox = QVBoxLayout()
add = QPushButton("+")
add.clicked.connect(self.add_new_stuff)
vbox.addWidget(add)
sub = QPushButton("-")
sub.clicked.connect(self.remove_selected_stuff)
vbox.addWidget(sub)
vbox.addStretch(1)
hbox.addLayout(vbox)
# 3: Separate the view of the data from the data itself. Use Model-View-Controller design to achieve this.
self.model = model
self.stuffview = QListView()
self.stuffview.setModel(self.model)
hbox.addWidget(self.stuffview)
def add_new_stuff(self):
new_stuff, success = QInputDialog.getText(self, 'Add stuff', 'Enter new stuff you want')
if success:
self.stuff.setStringList(self.stuff.stringList() + [new_stuff])
def remove_selected_stuff(self):
index = self.stuffview.currentIndex()
all_stuff = self.stuff.stringList()
del all_stuff[index.column()]
self.stuff.setStringList(all_stuff)
def window():
apk = QApplication(sys.argv)
# Data is clearly separated:
# 4: Never enumerate variables! Use lists!
stuff = QStringListModel(["Foo", "Bar", "Baz"])
# The graphical components is just how you interface with the data with the user!
win = StuffViewer(stuff)
win.show()
sys.exit(apk.exec_())
window()

How to add widgets dynamically upon selecting an option from QComboBox in Pyqt5

I want to add widgets in GUI when a user selects a particular item from QComboBox.
With the different options in combo-box Pip config, I want GUI to look like as in the following images. In the right image, there are extra widgets present for an item Multi pip. Also I want the location of the extra widgets as shown in the right image.
How to add these widgets dynamically ? Please find the code below.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt, QRect
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
vbox = QVBoxLayout()
CpsLabel = QLabel()
CpsLabel.setText("<font size = 12>Cps</font>")
CpsLabel.setAlignment(Qt.AlignCenter)
CpsLabel.setTextFormat(Qt.RichText)
CpsPipConfigLabel = QLabel('Pip config: ')
CpsPipConfigComboBox = QComboBox()
CpsPipConfigComboBox.addItems(['Single pip', 'Dual pip', 'Multi pip'])
CpsPipConfigComboBox.setCurrentIndex(2)
CpsChannel = QLabel('Cps channel: ')
CpsChannelComboBox = QComboBox()
CpsChannelComboBox.addItems(['A', 'B', 'C', 'D'])
CpsChannelComboBox.setCurrentIndex(0)
CpsTotalTeethLabel = QLabel('Total teeth: ')
CpsTotalTeethEdit = QLineEdit()
CpsTotalTeethEdit.setFixedWidth(50)
CpsTotalTeethEdit.setPlaceholderText('18')
CpsTotalTeethEdit.setValidator(QIntValidator())
CpsMissingTeethLabel = QLabel('Missing teeth: ')
CpsMissingTeethEdit = QLineEdit()
CpsMissingTeethEdit.setFixedWidth(50)
CpsMissingTeethEdit.setPlaceholderText('1')
CpsMissingTeethEdit.setValidator(QIntValidator())
vbox.addWidget(CpsLabel)
vbox.addStretch()
CpsQHBox1 = QHBoxLayout()
CpsQHBox1.setSpacing(0)
CpsQHBox1.addStretch()
CpsQHBox1.addWidget(CpsPipConfigLabel)
CpsQHBox1.addWidget(CpsPipConfigComboBox)
CpsQHBox1.addStretch()
vbox.addLayout(CpsQHBox1)
vbox.addStretch()
CpsQHBox2 = QHBoxLayout()
CpsQHBox2.setSpacing(0)
CpsQHBox2.addStretch()
CpsQHBox2.addSpacing(20)
CpsQHBox2.addWidget(CpsTotalTeethLabel)
CpsQHBox2.addWidget(CpsTotalTeethEdit)
CpsQHBox2.addStretch()
CpsQHBox2.addWidget(CpsMissingTeethLabel)
CpsQHBox2.addWidget(CpsMissingTeethEdit)
CpsQHBox2.addStretch()
vbox.addLayout(CpsQHBox2)
vbox.addStretch()
CpsQHBox3 = QHBoxLayout()
CpsQHBox3.setSpacing(0)
CpsQHBox3.addStretch()
CpsQHBox3.addWidget(CpsChannel)
CpsQHBox3.addWidget(CpsChannelComboBox)
CpsQHBox3.addStretch()
vbox.addLayout(CpsQHBox3)
vbox.addStretch()
self.setLayout(vbox)
self.setGeometry(200, 100, 300, 300)
self.setWindowTitle('Steady state data processing')
self.setWindowIcon(QIcon('duty_vs_suction_map_sum.png'))
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), QColor(255,250,100))
# p.setColor(self.backgroundRole(), Qt.blue)
self.setPalette(p)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
I suggest you set the widgets up and place them at the beginning like you have them, but set them invisible. Then make a method that sets the appropriate widgets visible based on the qcombobox's current text and connect it to the qcombobox's activated signal.
You will also need to add self in front of almost every object so that it can be referred to from other methods.
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
# setup code here...
self.CpsTotalTeethEdit.setVisible(False)
self.CpsTotalTeethLabel.setVisible(False)
self.CpsPipConfigComboBox.activated.connect(self.setup_total_teeth)
self.show()
def setup_widgets(self):
if self.CpsPipConfigComboBox.currentText() == "Multi pip":
self.CpsTotalTeethLabel.setVisible(True)
self.CpsTotalTeethEdit.setVisible(True)
By setting the items invisible instead of adding them with this method, you can also set them to be not visible when the cobobox's position is not for them.

Pyside crashes when executing function twice

Why does my application crash when i run the function setup_controls() twice.
Am I missing a 'parent/self' somewhere that is critical in the design?
import sys
from PySide import QtGui, QtCore
class QCategoryButton(QtGui.QPushButton):
def __init__(self, Text, treeitem, parent=None):
super(QCategoryButton, self).__init__(Text, parent)
self.treeitem = treeitem
def mousePressEvent(self, event):
mouse_button = event.button()
if mouse_button == QtCore.Qt.LeftButton:
self.treeitem.setExpanded(not self.treeitem.isExpanded())
class Example(QtGui.QWidget):
def __init__(self,):
super(Example, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(300, 300)
self.setWindowTitle("Example")
# widgets
self.ui_treeWidget = QtGui.QTreeWidget()
self.ui_treeWidget.setRootIsDecorated(False)
self.ui_treeWidget.setHeaderHidden(True)
self.ui_treeWidget.setIndentation(0)
self.setup_controls()
# self.setup_controls()
# layout
self.mainLayout = QtGui.QGridLayout(self)
self.mainLayout.addWidget(self.ui_treeWidget)
self.show()
def setup_controls(self):
# Add Category
pCategory = QtGui.QTreeWidgetItem()
self.ui_treeWidget.addTopLevelItem(pCategory)
self.ui_toggler = QCategoryButton('Settings', pCategory)
self.ui_treeWidget.setItemWidget(pCategory, 0, self.ui_toggler)
pFrame = QtGui.QFrame(self.ui_treeWidget)
pLayout = QtGui.QVBoxLayout(pFrame)
self.ui_ctrl = QtGui.QPushButton('Great')
self.ui_ctrlb = QtGui.QPushButton('Cool')
pLayout.addWidget(self.ui_ctrl)
pLayout.addWidget(self.ui_ctrlb)
pContainer = QtGui.QTreeWidgetItem()
pContainer.setDisabled(False)
pCategory.addChild(pContainer)
self.ui_treeWidget.setItemWidget(pContainer, 0, pFrame)
# Main
# ------------------------------------------------------------------------------
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
The setItemWidget method takes ownership of the widget that is passed to it. If you don't keep a reference it, it could get garbage-collected by Python. But of course Qt knows nothing about Python, so when it subsequently tries to access the widget that is no longer there ... boom!
This is the problematic line:
self.ui_toggler = QCategoryButton('Settings', pCategory)
On the second call, the previous widget stored in self.ui_toggler will get deleted, because there is no other reference held for it (on the Python side). So instead you should do this:
ui_toggler = QCategoryButton('Settings', pCategory, self)
self.ui_treeWidget.setItemWidget(pCategory, 0, ui_toggler)

Wrong widget order using vbox layout PyQt

I am trying to put a QLabel widget on top of (ie before) a QLineEdit widget edit.
But it keeps appearing after the QLineEdit widget. My code,
class CentralWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(CentralWidget, self).__init__(parent)
# set layouts
self.layout = QtGui.QVBoxLayout(self)
# Flags
self.randFlag = False
self.sphereFlag = False
self.waterFlag = False
# Poly names
self.pNames = QtGui.QLabel("Import file name", self) # label concerned
self.polyNameInput = QtGui.QLineEdit(self) # line edit concerned
# Polytype selection
self.polyTypeName = QtGui.QLabel("Particle type", self)
polyType = QtGui.QComboBox(self)
polyType.addItem("")
polyType.addItem("Random polyhedra")
polyType.addItem("Spheres")
polyType.addItem("Waterman polyhedra")
polyType.activated[str].connect(self.onActivated)
self.layout.addWidget(self.pNames)
self.layout.addWidget(self.polyNameInput)
self.layout.addWidget(self.pNames)
self.layout.addWidget(self.polyTypeName)
self.layout.addWidget(polyType)
self.layout.addStretch()
def onActivated(self, text):
# Do loads of clever stuff that I'm not at liberty to share with you
class Polyhedra(QtGui.QMainWindow):
def __init__(self):
super(Polyhedra, self).__init__()
self.central_widget = CentralWidget(self)
self.setCentralWidget(self.central_widget)
# Set up window
self.setGeometry(500, 500, 300, 300)
self.setWindowTitle('Pyticle')
self.show()
# Combo box
def onActivated(self, text):
self.central_widget.onActivated(text)
def main():
app = QtGui.QApplication(sys.argv)
poly = Polyhedra()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The window I get is below.
What am I missing? I thought QVbox allowed to stack things vertically in the order that you add the items to the main widget. (Are these sub-widget objects called widgets?)
The problem is because you are adding self.pNames label to layout twice.
#portion of your code
...
self.layout.addWidget(self.pNames) # here
self.layout.addWidget(self.polyNameInput)
self.layout.addWidget(self.pNames) # and here
self.layout.addWidget(self.polyTypeName)
self.layout.addWidget(polyType)
self.layout.addStretch()
...
The first time you add the QLabel, it gets added before the LineEdit and when you add it second time, it just moves to the bottom of LineEdit. This happens because there is only one object of QLabel which is self.pNames. It can be added to only one location. If you want to use two labels, consider creating two separate objects of QLabel

What happens with QMainWindow

I want to create the GUI with this code. When i click Add New Object Button, it will show the pop up (I use QMainWindown) but i want to put the QLabel in here, it can not work
I dont know why.i hope everyone can give me more some advices. Thanks you
This is my code :
from PySide import QtCore, QtGui
import sys
app = QtGui.QApplication.instance()
if not app:
app = QtGui.QApplication([])
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.mainLayout = QtGui.QGridLayout()
self.mainLayout.addWidget(self.First(), 0, 0, 2, 0)
self.setLayout(self.mainLayout)
self.setWindowTitle("Library")
self.resize(700,660)
#----------------------------------------FIRST COLUMN-------------------------------------
def First(self):
FirstFrame = QtGui.QFrame()
FirstFrame.setFixedSize(230,700)
# LABEL
renderer_lb = QtGui.QLabel("Renderer :")
folders_lb = QtGui.QLabel("Folder :")
#COMBOBOX
self.renderer_cbx = QtGui.QComboBox()
self.renderer_cbx.addItem("Vray")
self.renderer_cbx.addItem("Octane")
# LIST VIEW FOLDER
self.folders_lv = QtGui.QListView()
# BUTTON
addnewobject_btn = QtGui.QPushButton("Add New Objects")
newset_btn = QtGui.QPushButton("New Set")
# DEFINE THE FUNCTION FOR FIRST FRAME
Firstbox = QtGui.QGridLayout()
Firstbox.addWidget(renderer_lb,0,0)
Firstbox.addWidget(folders_lb,2,0,1,4)
Firstbox.addWidget(self.renderer_cbx,0,1,1,3)
Firstbox.addWidget(self.folders_lv,3,0,1,4)
Firstbox.addWidget(addnewobject_btn,4,0,1,2)
Firstbox.addWidget(newset_btn,4,3)
Firstbox.setColumnStretch(1, 1)
FirstFrame.setLayout(Firstbox)
addnewobject_btn.clicked.connect(self.addnewobject)
return FirstFrame
def addnewobject(self):
window = QtGui.QMainWindow(self)
window.setWindowTitle('Select folder of new objects')
window.setFixedSize(450,90)
window.show()
folder_lb = QtGui.QLabel("Folder : ")
browser = QtGui.QGridLayout()
browser.addWidget(folder_lb,0,0)
window.setLayout(browser)
if __name__ == '__main__':
window = Window()
sys.exit(window.exec_())
Just as you did in the First() function, you could create an homemade widget using QFrame. Then you can set a central widget for your new window.
from PySide import QtCore, QtGui
import sys
app = QtGui.QApplication.instance()
if not app:
app = QtGui.QApplication([])
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.mainLayout = QtGui.QGridLayout()
self.mainLayout.addWidget(self.First(), 0, 0, 2, 0)
self.setLayout(self.mainLayout)
self.setWindowTitle("Library")
self.resize(700,660)
self.show()
#----------------------------------------FIRST COLUMN-------------------------------------
def First(self):
FirstFrame = QtGui.QFrame()
FirstFrame.setFixedSize(230,700)
# LABEL
renderer_lb = QtGui.QLabel("Renderer :")
folders_lb = QtGui.QLabel("Folder :")
#COMBOBOX
self.renderer_cbx = QtGui.QComboBox()
self.renderer_cbx.addItem("Vray")
self.renderer_cbx.addItem("Octane")
# LIST VIEW FOLDER
self.folders_lv = QtGui.QListView()
# BUTTON
addnewobject_btn = QtGui.QPushButton("Add New Objects")
newset_btn = QtGui.QPushButton("New Set")
# DEFINE THE FUNCTION FOR FIRST FRAME
Firstbox = QtGui.QGridLayout()
Firstbox.addWidget(renderer_lb,0,0)
Firstbox.addWidget(folders_lb,2,0,1,4)
Firstbox.addWidget(self.renderer_cbx,0,1,1,3)
Firstbox.addWidget(self.folders_lv,3,0,1,4)
Firstbox.addWidget(addnewobject_btn,4,0,1,2)
Firstbox.addWidget(newset_btn,4,3)
Firstbox.setColumnStretch(1, 1)
FirstFrame.setLayout(Firstbox)
addnewobject_btn.clicked.connect(self.addnewobject)
return FirstFrame
def addnewobject(self):
secondFrame = QtGui.QFrame()
secondFrame.setFixedSize(230,700)
# LABEL
folders_lb = QtGui.QLabel("Folder :")
# DEFINE THE FUNCTION FOR FIRST FRAME
secondGridLayout = QtGui.QGridLayout()
secondGridLayout.addWidget(folders_lb,2,0,1,4)
secondGridLayout.setColumnStretch(1, 1)
secondFrame.setLayout(secondGridLayout)
window = QtGui.QMainWindow(self)
window.setWindowTitle('Select folder of new objects')
window.setFixedSize(600,700)
window.setCentralWidget(secondFrame) # Here is the main change: setLayout(QLayout) to setCentralWidget(QWidget)
window.show()
if __name__ == '__main__':
window = Window()
sys.exit(window.exec_())
Is this intended for Maya? If yes, I recommand you not to use modal windows as it will quickly fed up the users.

Categories