What happens with QMainWindow - python

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.

Related

Center subwindows in qmdiarea

Is there an attribute to position subwindows in qmdiarea? I’m trying to center subwindow in middle of mainwindow on startup (mdiarea)
I’m working on a mcve but haven’t finished it, wanted to see if anyone has tried doing this, and how they did it
Subwindows are randomly placed on startup when initialized
class App(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent=parent)
self.setupUi(self)
self.screenShape = QDesktopWidget().screenGeometry()
self.width = self.screenShape.width()
self.height = self.screenShape.height()
self.resize(self.width * .6, self.height * .6)
self.new = []
#calls GUI's in other modules
self.lw = Login()
self.vs = VS()
self.ms = MS()
self.hw = HomeWindow()
self.mw = MainWindow()
self.ga = GA()
self.sGUI = Settings()
# shows subwindow
self.CreateLogin()
self.CreateVS()
self.CreateMS()
self.CreateGA()
self.CreateSettings()
def CreateLogin(self):
self.subwindow = QMdiSubWindow()
self.subwindow.setWidget(self.lw)
self.subwindow.setAttribute(Qt.WA_DeleteOnClose, True)
self.mdiArea.addSubWindow(self.subwindow)
self.subwindow.setMaximumSize(520, 300)
self.subwindow.setMinimumSize(520, 300)
self.lw.showNormal()
def CreateVS(self):
self.subwindow = QMdiSubWindow()
self.subwindow.setWidget(self.vs)
self.mdiArea.addSubWindow(self.subwindow)
self.vs.showMinimized()
def CreateMS(self):
self.subwindow = QMdiSubWindow()
self.subwindow.setWidget(self.ms)
self.mdiArea.addSubWindow(self.subwindow)
self.ms.showMinimized()
self.ms.tabWidget.setCurrentIndex(0)
def CreateGA(self):
self.subwindow = QMdiSubWindow()
self.subwindow.setWidget(self.ga)
self.mdiArea.addSubWindow(self.subwindow)
self.ga.showMinimized()
self.subwindow.setMaximumSize(820, 650)
def CreateSettings(self):
self.subwindow = QMdiSubWindow()
self.subwindow.setWidget(self.sGUI)
self.mdiArea.addSubWindow(self.subwindow)
self.sGUI.showMinimized()
def CreateWindow(self):
self.hw.pushButton.clicked.connect(self.vs.showNormal)
self.hw.pushButton_2.clicked.connect(self.Moduleprogram)
self.hw.pushButton_3.clicked.connect(self.ms.showNormal)
self.hw.pushButton_4.clicked.connect(self.ga.showNormal)
self.subwindow = QMdiSubWindow()
self.subwindow.setWindowFlags(Qt.CustomizeWindowHint | Qt.Tool)
self.subwindow.setWidget(self.hw)
self.subwindow.setMaximumSize(258, 264)
self.subwindow.move(self.newwidth*.35, self.newheight*.25)
self.mdiArea.addSubWindow(self.subwindow)
In Qt the geometry is only effective when the window is visible so if you want to center something it must be in the showEvent method. On the other hand to center the QMdiSubWindow you must first get the center of the viewport of the QMdiArea, and according to that modify the geometry of the QMdiSubWindow.
Because the code you provide is complicated to execute, I have created my own code
from PyQt5 import QtCore, QtGui, QtWidgets
import random
def create_widget():
widget = QtWidgets.QLabel(
str(random.randint(0, 100)), alignment=QtCore.Qt.AlignCenter
)
widget.setStyleSheet(
"""background-color: {};""".format(
QtGui.QColor(*random.sample(range(255), 3)).name()
)
)
widget.setMinimumSize(*random.sample(range(100, 300), 2))
return widget
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
add_button = QtWidgets.QPushButton(
"Add subwindow", clicked=self.add_subwindow
)
self._mdiarea = QtWidgets.QMdiArea()
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QVBoxLayout(central_widget)
lay.addWidget(add_button)
lay.addWidget(self._mdiarea)
self._is_first_time = True
for _ in range(4):
self.add_subwindow()
#QtCore.pyqtSlot()
def add_subwindow(self):
widget = create_widget()
subwindow = QtWidgets.QMdiSubWindow(self._mdiarea)
subwindow.setWidget(widget)
subwindow.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
subwindow.show()
self._mdiarea.addSubWindow(subwindow)
# self.center_subwindow(subwindow)
def showEvent(self, event):
if self.isVisible() and self._is_first_time:
for subwindow in self._mdiarea.subWindowList():
self.center_subwindow(subwindow)
self._is_first_time = False
def center_subwindow(self, subwindow):
center = self._mdiarea.viewport().rect().center()
geo = subwindow.geometry()
geo.moveCenter(center)
subwindow.setGeometry(geo)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Update:
If you want the subwindow to be centered then with the following code you have to create a property center to True:
def add_subwindow(self):
widget = create_widget()
subwindow = QtWidgets.QMdiSubWindow(self._mdiarea)
subwindow.setWidget(widget)
subwindow.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
subwindow.show()
subwindow.setProperty("center", True) # <----
self._mdiarea.addSubWindow(subwindow)
def showEvent(self, event):
if self.isVisible() and self._is_first_time:
for subwindow in self._mdiarea.subWindowList():
if subwindow.property("center"): # <---
self.center_subwindow(subwindow)
self._is_first_time = False

Position internal widget inside QStackedWidget object

I have several tabs and inside the "admin" tab I want to display two pages: one locked page (before entering credentials) and another unlocked page (after successful login). To do this, I'm using a QStackedWidget() to switch between the two pages. I have created a locked login screen but can't seem to move the object to the center of the page.
I have looked at moving widgets inside QStackedWidget and centering widgets in the center of the screen but my objects do not seem to change position. I've tried to move the entire internal widget using move() to the center of the screen using the desktop dimension and the parent widget to no avail. How would I be able to move the login fields to the center of the page? Thanks!
Current:
Desired:
Code:
from PyQt4 import QtGui, QtCore
# from load_CSS import load_CSS
# from widgets import UniversalPlotWidget
import sys
import time
def exit_application():
"""Exit program event handler"""
sys.exit(1)
class VerticalTabBar(QtGui.QTabBar):
def __init__(self, width, height, parent=None):
super(VerticalTabBar, self).__init__(parent)
self.width = width
self.height = height
def tabSizeHint(self, index):
return QtCore.QSize(self.width, self.height)
def paintEvent(self, event):
painter = QtGui.QStylePainter(self)
tab_options = QtGui.QStyleOptionTab()
for tab in range(self.count()):
self.initStyleOption(tab_options, tab)
painter.drawControl(QtGui.QStyle.CE_TabBarTabShape, tab_options)
painter.save()
size = tab_options.rect.size()
size.transpose()
rectangle = QtCore.QRect(QtCore.QPoint(), size)
rectangle.moveCenter(tab_options.rect.center())
tab_options.rect = rectangle
center = self.tabRect(tab).center()
painter.translate(center)
painter.rotate(90)
painter.translate(-center)
painter.drawControl(QtGui.QStyle.CE_TabBarTabLabel, tab_options);
painter.restore()
class TabWidget(QtGui.QTabWidget):
def __init__(self, *args, **kwargs):
QtGui.QTabWidget.__init__(self, *args, **kwargs)
self.setTabBar(VerticalTabBar(kwargs.pop('width'), kwargs.pop('height')))
self.setTabPosition(QtGui.QTabWidget.West)
self.setTabShape(QtGui.QTabWidget.Rounded)
class AdminTabWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(AdminTabWidget, self).__init__(parent)
self.setWindowModality(QtCore.Qt.ApplicationModal)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.admin_page_locked_init()
self.admin_page_unlocked_init()
self.admin_page_layout = QtGui.QGridLayout()
self.admin_page_switch = QtGui.QStackedWidget()
self.admin_page_switch.addWidget(self.admin_locked_tab)
self.admin_page_switch.addWidget(self.admin_unlocked_tab)
self.admin_page_switch.setCurrentIndex(0)
self.admin_page_layout.addWidget(self.admin_page_switch,0,0)
def admin_page_locked_init(self):
self.admin_locked_tab = QtGui.QWidget()
self.admin_locked_tab.setFixedSize(550,225)
self.admin_locked_layout = QtGui.QGridLayout()
self.username_label = QtGui.QLabel('Username: ')
self.username_field = QtGui.QLineEdit()
self.username_field.returnPressed.connect(self.verify_credentials)
self.space_label = QtGui.QLabel(' ')
self.space_label.setFixedHeight(25)
self.password_label = QtGui.QLabel('Password: ')
self.password_field = QtGui.QLineEdit()
self.password_field.returnPressed.connect(self.verify_credentials)
self.password_field.setEchoMode(QtGui.QLineEdit.Password)
self.verify_button = QtGui.QPushButton('Ok')
self.verify_button.clicked.connect(self.verify_credentials)
self.cancel_button = QtGui.QPushButton('Cancel')
self.cancel_button.clicked.connect(self.unauthorized)
self.status_label = QtGui.QLabel('')
self.status_label.setAlignment(QtCore.Qt.AlignCenter)
self.button_layout = QtGui.QGridLayout()
self.button_layout.addWidget(self.verify_button,0,0,1,1)
self.button_layout.addWidget(self.cancel_button,0,1,1,1)
self.admin_locked_layout.addWidget(self.username_label,0,0,1,1)
self.admin_locked_layout.addWidget(self.username_field,0,1,1,1)
self.admin_locked_layout.addWidget(self.space_label,1,0,1,3)
self.admin_locked_layout.addWidget(self.password_label,2,0,1,1)
self.admin_locked_layout.addWidget(self.password_field,2,1,1,1)
self.admin_locked_layout.addWidget(self.status_label,3,0,1,3)
self.admin_locked_layout.addLayout(self.button_layout,4,0,1,3)
self.admin_locked_tab.setLayout(self.admin_locked_layout)
def verify_credentials(self):
print('button pressed')
# Grab username/password from input fields
self.username = str(self.username_field.text())
self.password = str(self.password_field.text())
self.status_label.setText('Verifying')
self.status_label.setStyleSheet('QLabel {color: rgb(117,255,161)}')
self.spin(.001)
print('verified')
def spin(self, seconds):
"""Pause for set amount of seconds, replaces time.sleep so program doesnt stall"""
time_end = time.time() + seconds
while time.time() < time_end:
QtGui.QApplication.processEvents()
def unauthorized(self):
print('unauthorized')
self.status_label.setText('Invalid username and/or password')
self.status_label.setStyleSheet('QLabel {color: rgb(255,65,106)}')
def admin_page_unlocked_init(self):
self.admin_unlocked_tab = QtGui.QWidget()
admin_unlocked_layout = QtGui.QGridLayout()
admin_unlocked_button = QtGui.QPushButton('unlocked')
admin_unlocked_layout.addWidget(admin_unlocked_button)
self.admin_unlocked_tab.setLayout(admin_unlocked_layout)
def get_admin_page_layout(self):
return self.admin_page_layout
if __name__ == '__main__':
# Create main application window
app = QtGui.QApplication(sys.argv)
# app.setStyleSheet(load_CSS(1))
app.setStyle(QtGui.QStyleFactory.create("Cleanlooks"))
font = QtGui.QFont('Ubuntu', 20)
font.setWeight(70)
app.setFont(font)
screen_height = QtGui.QApplication.desktop().screenGeometry().height()
main_window_tab = TabWidget(width=300, height=screen_height/8)
main_window_tab.setWindowTitle("Tab Layout")
main_window_tab.setWindowFlags(QtCore.Qt.FramelessWindowHint)
main_window_tab.showMaximized()
tab1 = QtGui.QWidget()
tab2 = QtGui.QWidget()
tab3 = QtGui.QWidget()
tab4 = QtGui.QWidget()
tab5 = QtGui.QWidget()
tab6 = QtGui.QWidget()
tab7 = QtGui.QWidget()
admin_tab = QtGui.QWidget()
admin_tab_widget = AdminTabWidget()
admin_tab.setLayout(admin_tab_widget.get_admin_page_layout())
main_window_tab.addTab(admin_tab, "Admin")
main_window_tab.addTab(tab1, "tab1")
main_window_tab.addTab(tab2, "tab2")
main_window_tab.addTab(tab3, "tab3")
main_window_tab.addTab(tab4, "tab4")
main_window_tab.addTab(tab5, "tab5")
main_window_tab.addTab(tab6, "tab6")
main_window_tab.addTab(tab7, "tab7")
main_window_tab.show()
QtGui.QShortcut(QtGui.QKeySequence('Ctrl+Q'), main_window_tab, exit_application)
sys.exit(app.exec_())
The idea is to set the QStackedWidget with the Qt::AlignCenter alignment in the layout so it changes:
self.admin_page_layout.addWidget(self.admin_page_switch, 0, 0)
to:
self.admin_page_layout.addWidget(self.admin_page_switch, 0, 0, alignment=QtCore.Qt.AlignCenter)

All the widgets disappear when window size is decreased

When I decrease the window size all the widgets disappear.I want the widgets to move along when size is decreased.How do I solve this problem?
I have a drop-down menu from which a value is selected.When an "Add cmd" button is pressed the value is added to edit box.
Thanks in advance.
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class tabdemo(QTabWidget):
def __init__(self, parent = None):
super(tabdemo, self).__init__(parent)
self.setGeometry(50, 50, 400,400)
QShortcut(QKeySequence("Esc"), self, self.close)
self.tab1 = QWidget()
self.tab2 = QWidget()
self.addTab(self.tab1,"Tab 1")
self.tab1UI()
self.setWindowTitle("Main Window")
def tab1UI(self):
self.comboBox = QComboBox(self.tab1)
self.comboBox.addItem('ABC')
self.comboBox.addItem('BCD')
self.comboBox.addItem('CDE')
self.comboBox.move(5,20)
self.comboBox.resize(180,30)
self.button = QPushButton('Add Cmd', self.tab1)
self.button.move(190,20)
self.button.resize(80,30)
self.button.clicked.connect(self.handleTest)
self.b = QTextEdit(self.tab1)
self.b.move(20,75)
self.b.resize(290,200)
self.button = QPushButton('Send Batch', self.tab1)
self.button.move(40,300)
self.button.resize(150,30)
self.button = QPushButton('Clear', self.tab1)
self.button.move(200,300)
self.button.resize(80,30)
self.button.clicked.connect(self.deletevalue)
layout = QFormLayout()
self.setTabText(4,"BatchCMDS")
self.tab1.setLayout(layout)
def handleTest(self):
self.b.append(str(self.comboBox.currentText()))
def deletevalue(self):
self.b.clear()
def main():
app = QApplication(sys.argv)
ex = tabdemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
If you want the widgets to adapt to the size of the window you should use layouts, For this, the application must be designed, for this an image is used of how you want your application to be:
As we see the widgets that are inside a tab are divided into 3 groups, the first is made up of the QComboBox with the QPushButton, the second the QTextEdit, and the third the 2 remaining buttons. Each group is horizontally distributed, so in that case we should use QHBoxLayout except the QTextEdit that is alone, and each group should be in QVBoxLayout. I do not understand why you use the QFormLayout, also if you use the layouts the positions are not necessary.
Another error that I see in your code is that several buttons have the same name, this causes errors like for example that the Add CMD button does not work, you must give a different name to each widget.
class tabdemo(QTabWidget):
def __init__(self, parent = None):
super(tabdemo, self).__init__(parent)
self.setGeometry(50, 50, 400,400)
QShortcut(QKeySequence("Esc"), self, self.close)
self.tab1 = QWidget()
self.tab2 = QWidget()
self.addTab(self.tab1,"Tab 1")
self.addTab(self.tab2,"Tab 2")
self.tab1UI()
def tab1UI(self):
vlayout = QVBoxLayout(self.tab1)
hlayout1 = QHBoxLayout()
self.comboBox = QComboBox(self.tab1)
self.comboBox.addItems(['ABC', 'BCD', 'CDE'])
self.button = QPushButton('Add Cmd', self.tab1)
self.button.clicked.connect(self.handleTest)
hlayout1.addWidget(self.comboBox)
hlayout1.addWidget(self.button)
hlayout1.addItem(QSpacerItem(100, 10, QSizePolicy.Expanding, QSizePolicy.Preferred))
vlayout.addLayout(hlayout1)
self.b = QTextEdit(self.tab1)
vlayout.addWidget(self.b)
hlayout2 = QHBoxLayout()
self.buttonSend = QPushButton('Send Batch', self.tab1)
self.buttonClear = QPushButton('Clear', self.tab1)
self.buttonClear.clicked.connect(self.deletevalue)
hlayout2.addItem(QSpacerItem(100, 10, QSizePolicy.Expanding, QSizePolicy.Preferred))
hlayout2.addWidget(self.buttonSend)
hlayout2.addWidget(self.buttonClear)
hlayout2.addItem(QSpacerItem(100, 10, QSizePolicy.Expanding, QSizePolicy.Preferred))
vlayout.addLayout(hlayout2)
self.setTabText(4,"BatchCMDS")
def handleTest(self):
self.b.append(self.comboBox.currentText())
def deletevalue(self):
self.b.clear()

Add custom items to QListWidget

How can I add customized items to a QListWidget with a background color that I choose, and add a bottom border to each item, like this draft example in the picture below.
This is the code that I wrote:
from PyQt5 import QtWidgets, QtGui
import sys
class CustomListHead(QtWidgets.QWidget):
def __init__(self):
super(CustomListHead, self).__init__()
self.project_title = QtWidgets.QLabel("Today")
self.set_ui()
def set_ui(self):
grid_box = QtWidgets.QGridLayout()
grid_box.addWidget(self.project_title, 0, 0)
self.setLayout(grid_box)
self.show()
class CustomListItem(QtWidgets.QWidget):
def __init__(self):
super(CustomListItem, self).__init__()
self.project_title = QtWidgets.QLabel("Learn Python")
self.task_title = QtWidgets.QLabel("Learn more about forms, models and include")
self.set_ui()
def set_ui(self):
grid_box = QtWidgets.QGridLayout()
grid_box.addWidget(self.project_title, 0, 0)
grid_box.addWidget(self.task_title, 1, 0)
self.setLayout(grid_box)
self.show()
class MainWindowUI(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindowUI, self).__init__()
self.list_widget = QtWidgets.QListWidget()
self.set_ui()
def set_ui(self):
custom_head_item = CustomListHead()
item = QtWidgets.QListWidgetItem(self.list_widget)
item.setSizeHint(custom_head_item.sizeHint())
self.list_widget.setItemWidget(item, custom_head_item)
self.list_widget.addItem(item)
custom_item = CustomListItem()
item = QtWidgets.QListWidgetItem(self.list_widget)
item.setSizeHint(custom_item.sizeHint())
self.list_widget.addItem(item)
self.list_widget.setItemWidget(item, custom_item)
vertical_layout = QtWidgets.QVBoxLayout()
vertical_layout.addWidget(self.list_widget)
widget = QtWidgets.QWidget()
widget.setLayout(vertical_layout)
self.setCentralWidget(widget)
self.show()
app = QtWidgets.QApplication(sys.argv)
ui = MainWindowUI()
sys.exit(app.exec_())
I see you have QListWidgetItem with you.
From documentation you can customize each widget item, customize it and add to your listwidget:
The appearance of the text can be customized with setFont(), setForeground(), and setBackground(). Text in list items can be aligned using the setTextAlignment() function. Tooltips, status tips and "What's This?" help can be added to list items with setToolTip(), setStatusTip(), an
d setWhatsThis().
http://doc.qt.io/qt-5/qlistwidgetitem.html#details

populate python qt widget with items from class

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_())

Categories