So basically I'm trying to make an updating QGroupBox with some QPushButtons inside of it, here's the "updating" method and it is always called right after the list is changed:
def repaintList(self):
btn_ls = []
for i in range(len(self.list)):
btn_ls.append(buttons.QPushButton("t"))
layout = QVBoxLayout()
for i in range(len(btn_ls)):
layout.addWidget(btn_ls[i])
it's pretty simple, I have a method that updates the list for me and I've tested the functionality with print(len(self.list)) and print(btn_ls) enough to know that the list updating works, and that the btn_ls is made properly, but I'm not sure why it's not updating on the actual screen.
I've made an example of a simplified version of what I'm trying to accomplish:
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class TestWindow(QWidget):
def __init__(self):
super(TestWindow,self).__init__()
self.list = []
self.cont = TestContainer(self.list, "Test Box", self)
self.adder = AdderButton("Add one", self, self.list, self.cont)
layout = QVBoxLayout()
layout.addWidget(self.cont)
self.setLayout(layout)
self.setGeometry(200,200,200,200)
class TestContainer(QGroupBox):
def __init__(self,ls,ttl,pare):
super(TestContainer,self).__init__(ttl,pare)
self.list = ls
self.repaintButtons()
def repaintButtons(self):
btn_ls = []
for i in range(len(self.list)):
btn_ls.append(QPushButton(str(i),self))
print(self.list)
layout = QVBoxLayout()
for i in range(len(btn_ls)):
layout.addWidget(btn_ls[i])
self.setLayout(layout)
class AdderButton(QPushButton):
def __init__(self,txt,pare,ls,displ):
super(AdderButton,self).__init__(txt,pare)
self.disp = displ
self.list = ls
self.clicked.connect(self.addOne)
def addOne(self):
self.list.append(1)
self.disp.repaintButtons()
def main():
app = QApplication(sys.argv)
tw = TestWindow()
tw.show()
app.exec()
if __name__ == "__main__":
main()
The desired result is that every time I press the button a new QPushButton would appear on the screen...
After doing more research, I came across the update() function which basically repaints the QGroupBox. It works in the sense that it adds one button at a time and updates each time a button is added.
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class TestWindow(QWidget):
def __init__(self):
super(TestWindow,self).__init__()
self.list = []
self.cont = TestContainer(self.list, "Test Box", self)
self.adder = AdderButton("Add one", self, self.list, self.cont)
layout = QVBoxLayout()
layout.addWidget(self.cont)
self.setLayout(layout)
self.setGeometry(200,200,200,200)
class TestContainer(QGroupBox):
def __init__(self,ls,ttl,pare):
super(TestContainer,self).__init__(ttl,pare)
self.list = ls
self.layout = QVBoxLayout()
self.setLayout(self.layout)
def addButton(self):
self.layout.addWidget(QPushButton("thing"))
class AdderButton(QPushButton):
def __init__(self,txt,pare,ls,displ):
super(AdderButton,self).__init__(txt,pare)
self.disp = displ
self.list = ls
self.clicked.connect(self.addOne)
def addOne(self):
self.list.append(1)
self.disp.addButton()
self.disp.update()
def main():
app = QApplication(sys.argv)
tw = TestWindow()
tw.show()
app.exec()
if __name__ == "__main__":
main()
I has to use self.layout() instead of layout to see widgets.
def repaintButtons(self):
btn_ls = []
for i in range(len(self.list)):
btn_ls.append(QPushButton(str(i),self))
print(self.list)
layout = QVBoxLayout()
self.setLayout(layout) # it has to be before `self.layout()`
for i in range(len(btn_ls)):
self.layout().addWidget(btn_ls[i])
BTW: self.setLayout() has to be before self.layout()
But there is other problem.
Using again
layout = QVBoxLayout()
self.setLayout(layout)
doesn't remove previous layout and it doesn't remove previous buttons and finally it adds again the same buttons to layout.
You would need add only new buttons to layout instead of adding all buttons again.
Or you would have to remove widgets from layout before adding them again.
EDIT:
Code which adds new button without removing previous buttons
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class TestWindow(QWidget):
def __init__(self):
super(TestWindow,self).__init__()
self.list = []
self.container = TestContainer("Test Box", self, self.list)
self.adder = AdderButton("Add one", self, self.container)
layout = QVBoxLayout()
layout.addWidget(self.container)
self.setLayout(layout)
self.setGeometry(200,200,200,200)
class TestContainer(QGroupBox):
def __init__(self, title, parent, lst):
super(TestContainer,self).__init__(title, parent)
self.list = lst
layout = QVBoxLayout()
self.setLayout(layout)
# create buttons at start using `self.list`
for item in self.list:
self.layout().addWidget(QPushButton(str(item), self))
def addButton(self, item):
# add new item to `self.list` and create new button
self.list.append(item)
self.layout().addWidget(QPushButton(str(item), self))
class AdderButton(QPushButton):
def __init__(self, text, parent, target):
super(AdderButton,self).__init__(text, parent)
self.target = target
self.clicked.connect(self.addOne)
def addOne(self):
self.target.addButton(1)
def main():
app = QApplication(sys.argv)
tw = TestWindow()
tw.show()
app.exec()
if __name__ == "__main__":
main()
There are examples how to remove items but they don't work for me
Clear all widgets in a layout in pyqt
PyQt How to remove a layout from a layout
Related
I have a complex program in which I need to connect multiple windows. Unfortunately, I seem to be not fully understanding the concept/steps necessary to do this so bonus points if anyone can explain the steps/process well. In my current program, I have a list of items. Once I select them by moving them over to the right list widget, I need them to go to the third window. The third window should be activated by clicking the dots on the second window. The program runs and shows the second window appropriately but the signal/slot connection of the dots button does not work. However, the rest of the code is working because if I switch the toolkit to show the third window, that part is performing as expected. My code is below, and again, no errors are being returned, but clicking the dots button on the second window does nothing.
Also, a question - do I instantiate the third window within the second class, or only within the main window? Again, struggling to fully understand the process and I will need to do this multiple more times.
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QListWidget, QLineEdit, QTextEdit, QGridLayout, QHBoxLayout, QVBoxLayout, QSizePolicy, QFileDialog, QTabWidget, QCheckBox
import PyQt5.QtGui as qtg
import glob
import os
from PyQt5.QtCore import Qt, QSettings
import inspect
from PyQt5 import QtCore
import pandas as pd
import pathlib
import pyreadstat
import json
class ThirdWindow(QWidget):
def __init__(self):
super().__init__()
self.layout = QGridLayout()
self.setLayout(self.layout)
self.allVariables = QListWidget()
self.variablesSelected = QListWidget()
#self.allVariables.insertItem(0, 'Hello')
self.layout.addWidget(self.allVariables, 1,0)
self.layout.addWidget(self.variablesSelected, 1, 1)
def setItems(self, items):
self.allVariables.clear()
for item in items:
self.allVariables.addItem(item)
class SecondWindow(QWidget):
def __init__(self):
super().__init__()
##not sure if I am supposed to instantiate this here or only in the main window class
self.thirdWindow = ThirdWindow()
self.layout = QGridLayout(self)
self.by = QLabel("By")
self.byVariables = QLineEdit()
self.byButton = QPushButton("...")
self.layout.addWidget(self.by, 1, 0)
self.layout.addWidget(self.byVariables, 2, 0)
self.layout.addWidget(self.byButton, 2, 1)
def seconddWindowConnections(self):
self.byButton.clicked.connect(self.show_third_window)
#self.buttons['Toolkit'].clicked.connect(self.show_new_window)
def show_third_window(self):
self.thirdWindow.show()
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# Add a title
self.setWindowTitle("GUI Querying Program")
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.initUI()
self.setButtonConnections()
self.sw = SecondWindow()
self.tw = ThirdWindow()
def initUI(self):
subLayouts = {}
subLayouts['LeftColumn'] = QGridLayout()
self.layout.addLayout(subLayouts['LeftColumn'],1)
# Buttons
self.buttons = {}
self.buttons['addVariable'] = QPushButton('>')
self.buttons['removeVariable'] = QPushButton('<')
self.buttons['Toolkit'] = QPushButton('Toolkit')
self.variables = QListWidget()
self.selectedVariables = QListWidget()
subLayouts['LeftColumn'].addWidget(self.variables, 7,0,4,1)
subLayouts['LeftColumn'].addWidget(self.selectedVariables, 7,1,4,1)
subLayouts['LeftColumn'].addWidget(self.buttons['addVariable'], 10,0,1,1)
subLayouts['LeftColumn'].addWidget(self.buttons['removeVariable'], 10,1,1,1)
subLayouts['LeftColumn'].addWidget(self.buttons['Toolkit'], 11,1,1,1)
names = ['apple', 'banana', 'Cherry']
self.variables.insertItems(0, names)
def setButtonConnections(self):
self.buttons['addVariable'].clicked.connect(self.add_variable)
self.buttons['Toolkit'].clicked.connect(self.show_new_window)
self.buttons['Toolkit'].clicked.connect(self.add_selected_variables)
def add_variable(self):
for item in self.variables.selectedItems():
self.selectedVariables.addItem(item.clone())
def show_new_window(self):
self.sw.show()
def add_selected_variables(self):
items = []
for i in range(self.selectedVariables.count()):
items.append(self.selectedVariables.item(i).clone())
self.tw.setItems(items)
if __name__ == "__main__":
import sys
app = QApplication([])
mw = MainWindow()
mw.show()
app.exec()
The main issue with your code is that secondWindowConnections is never called so the button actually does nothing. I corrected that and fixed a few other issues I found in my example below. I left out the bits where I made no changes and all the changes I did make I made inline notes explaining them:
class SecondWindow(QWidget):
def __init__(self):
super().__init__()
self.thirdWindow = None # dont initialize until neccessary
self.thirdWindowItems = []
self.layout = QGridLayout(self)
self.by = QLabel("By")
self.byVariables = QLineEdit()
self.byButton = QPushButton("...")
self.layout.addWidget(self.by, 1, 0)
self.layout.addWidget(self.byVariables, 2, 0)
self.layout.addWidget(self.byButton, 2, 1)
self.secondWindowConnections() # Run this to setup the
# signal for the third window.
def secondWindowConnections(self): # this had a typo
self.byButton.clicked.connect(self.show_third_window)
def show_third_window(self):
if self.thirdWindow is None: # if window has been created yet
self.thirdWindow = ThirdWindow() # create window
if not self.thirdWindow.isVisible(): # if window is showing
self.thirdWindow.show() # show window
self.thirdWindow.setItems(self.thirdWindowItems) # send items to window
def send_items(self, items): # this is to collect the variable that
self.thirdWindowItems = items # move to the third window
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# Add a title
self.setWindowTitle("GUI Querying Program")
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.initUI()
self.setButtonConnections()
self.sw = None # dont initialize until neccessary.
def initUI(self):
subLayouts = {}
subLayouts['LeftColumn'] = QGridLayout()
self.layout.addLayout(subLayouts['LeftColumn'],1)
self.buttons = {}
self.buttons['addVariable'] = QPushButton('>')
self.buttons['removeVariable'] = QPushButton('<')
self.buttons['Toolkit'] = QPushButton('Toolkit')
self.variables = QListWidget()
self.selectedVariables = QListWidget()
subLayouts['LeftColumn'].addWidget(self.variables, 7,0,4,1)
subLayouts['LeftColumn'].addWidget(self.selectedVariables, 7,1,4,1)
subLayouts['LeftColumn'].addWidget(self.buttons['addVariable'], 10,0,1,1)
subLayouts['LeftColumn'].addWidget(self.buttons['removeVariable'], 10,1,1,1)
subLayouts['LeftColumn'].addWidget(self.buttons['Toolkit'], 11,1,1,1)
names = ['apple', 'banana', 'Cherry']
self.variables.insertItems(0, names)
def setButtonConnections(self):
self.buttons['addVariable'].clicked.connect(self.add_variable)
self.buttons['Toolkit'].clicked.connect(self.show_new_window)
# self.buttons['Toolkit'].clicked.connect(self.add_selected_variables)
# only use one connnect slot
def add_variable(self):
for item in self.variables.selectedItems():
self.selectedVariables.addItem(item.clone())
def show_new_window(self):
if self.sw is None: # check if window has been constructed
self.sw = SecondWindow() # construct window
if not self.sw.isVisible(): # If winow is not showing
self.sw.show() # show window
self.sw.send_items(self.add_selected_variables()) # send selected
# variables to second window
def add_selected_variables(self):
items = []
for i in range(self.selectedVariables.count()):
items.append(self.selectedVariables.item(i).clone())
# self.tw.setItems(items) ... self.tw doesnt exist so return them
return items
layout
layout (1)
QlineEdit
Qpushbutton
layout (2)
QlineEdit
Qpushbutton
Qpushbutton (3)
I try to create and delete layout(1,2) in layout.
it's work real time. layout(1,2) are dynamic number (1,2,3,~~)
Qpushbutton click -> parent layout and widget delete
and query text in QlineEdit
my test code --
#-*- coding:utf-8 -*-
import maya.cmds as mc
import os
import pprint
from PySide2 import QtWidgets, QtCore, QtGui
class PreferenceUI(QtWidgets.QDialog):
def __init__(self):
super(PreferenceUI, self).__init__()
self.setWindowTitle("preference")
self.create_widgets()
self.create_layouts()
self.create_connections()
self.load_department()
def create_widgets(self):
self.departmentNameLine = QtWidgets.QLineEdit()
self.departmentNameLine.setFixedSize(100,20)
self.departmentPathLine = QtWidgets.QLineEdit()
self.departmentMinusBtn = QtWidgets.QPushButton("-")
self.departmentMinusBtn.setFixedSize(20,20)
self.departmentPlusBtn = QtWidgets.QPushButton("+")
self.sysAppendWidget = QtWidgets.QTextEdit()
def create_layouts(self):
self.mainLayout = QtWidgets.QFormLayout(self)
self.departmentLayout = QtWidgets.QVBoxLayout()
self.departmentLastLayout = QtWidgets.QHBoxLayout()
self.departmentLayout.addLayout(self.departmentLastLayout)
self.departmentLayout.addWidget(self.departmentPlusBtn)
self.mainLayout.addRow("department :", self.departmentLayout)
self.mainLayout.insertRow(self.mainLayout.count()-1, "sys.path.append :", self.sysAppendWidget)
def create_connections(self):
pass
def load_department(self):
self.departmentPlusBtn.setParent(None)
jsonDict = {"department": [["temp", "tempPath"], ["temp2", "temp2Path"]]}
for i in range(len(jsonDict["department"])):
layout = QtWidgets.QHBoxLayout()
self.departmentLayout.addLayout(layout)
departmentNameLine = QtWidgets.QLineEdit()
departmentNameLine.setText(jsonDict["department"][i][0])
departmentNameLine.setFixedSize(100,20)
departmentPathLine = QtWidgets.QLineEdit()
departmentPathLine.setText(jsonDict["department"][i][1])
departmentMinusBtn = QtWidgets.QPushButton("-")
departmentMinusBtn.setFixedSize(20,20)
cnt = self.departmentLayout.count()
departmentMinusBtn.clicked.connect(lambda x:self.remove_department(cnt))
layout.addWidget(departmentNameLine)
layout.addWidget(departmentPathLine)
layout.addWidget(departmentMinusBtn)
self.departmentLayout.insertWidget(self.departmentLayout.count(), self.departmentPlusBtn)
def remove_department(self, index):
print index
print self.departmentLayout.children()[0].layout().children()
if __name__ == "__main__":
try:
ui.close
except:
pass
ui = PreferenceUI()
ui.show()
I want
add path line
delete path line
query departmentNameLine, departmentPathLine text
i try ↑, but fail
i try in maya
To keep the logic tidy I have created a class that represents a row, then store the rows in a list to get the texts or to delete the row as I show below:
from functools import partial
from PySide2 import QtWidgets, QtCore, QtGui
class Widget(QtWidgets.QWidget):
def __init__(self, text1, text2, parent=None):
super().__init__(parent)
self.departmentNameLine = QtWidgets.QLineEdit(text1)
self.departmentNameLine.setFixedSize(100, 20)
self.departmentPathLine = QtWidgets.QLineEdit(text2)
self.departmentMinusBtn = QtWidgets.QPushButton("-")
self.departmentMinusBtn.setFixedSize(20, 20)
self.setContentsMargins(0, 0, 0, 0)
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.departmentNameLine)
layout.addWidget(self.departmentPathLine)
layout.addWidget(self.departmentMinusBtn)
class PreferenceUI(QtWidgets.QDialog):
def __init__(self):
super(PreferenceUI, self).__init__()
self.widgets = []
self.setWindowTitle("preference")
self.create_widgets()
self.create_layouts()
self.create_connections()
self.load_department()
def create_widgets(self):
self.departmentPlusBtn = QtWidgets.QPushButton("+")
self.sysAppendWidget = QtWidgets.QTextEdit()
def create_layouts(self):
self.mainLayout = QtWidgets.QFormLayout(self)
self.departmentLayout = QtWidgets.QVBoxLayout()
self.departmentLastLayout = QtWidgets.QHBoxLayout()
self.departmentLayout.addLayout(self.departmentLastLayout)
self.departmentLayout.addWidget(self.departmentPlusBtn)
self.mainLayout.addRow("department :", self.departmentLayout)
self.mainLayout.insertRow(
self.mainLayout.count() - 1, "sys.path.append :", self.sysAppendWidget
)
def create_connections(self):
self.departmentPlusBtn.clicked.connect(self.add_row)
def load_department(self):
jsonDict = {"department": [["temp", "tempPath"], ["temp2", "temp2Path"]]}
for text1, text2 in jsonDict["department"]:
self.create_row(text1, text2)
def save_departament(self):
l = []
for widget in self.widgets:
l.append([self.departmentNameLine.text(), self.departmentPathLine.text()])
jsonDict = {"department": l}
print(jsonDict)
def add_row(self):
self.create_row("text1", "text2")
def create_row(self, text1="", text2=""):
widget = Widget(text1, text2)
widget.departmentMinusBtn.clicked.connect(partial(self.delete, widget))
self.departmentLayout.addWidget(widget)
self.widgets.append(widget)
def delete(self, widget):
if widget in self.widgets:
self.widgets.remove(widget)
widget.deleteLater()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = PreferenceUI()
w.show()
sys.exit(app.exec_())
I am creating a Python PyQt5 app for a university project, which uses QStackedLayout to keep the app single-windowed.
First question: how can I create buttons that appear on every window and have the same function and property without having to recreate them in every window's UI setup (like in the code)?
Second question: after switching windows, how can I open the newly opened window at the previous's position? Right now they just open at the centre of the screen. I assume pos() or QPoint should be used but I can not figure out how.
import sys
from PyQt5.QtWidgets import (QApplication,
QMainWindow,
QPushButton,
QWidget,
QStackedLayout)
class Ui(QWidget):
def setupUi(self, Main):
self.application_width = 200
self.application_height = 200
self.stack = QStackedLayout()
self.window_1 = QWidget()
self.window_2 = QWidget()
self.window_1_UI()
self.window_2_UI()
self.stack.addWidget(self.window_1)
self.stack.addWidget(self.window_2)
def window_1_UI(self):
self.window_1.setFixedSize(self.application_width, self.application_height)
self.window_1.setWindowTitle("1")
'''REPLACE THIS BUTTON'''
self.window_1_button = QPushButton("Change window", self.window_1)
def window_2_UI(self):
self.window_2.setFixedSize(self.application_width, self.application_height)
self.window_2.setWindowTitle("2")
'''AND REPLACE THIS BUTTON'''
self.window_2_button = QPushButton("Change window", self.window_2)
class Main(QMainWindow, Ui):
def __init__(self):
super(Main, self).__init__()
self.setupUi(self)
self.window_1_button.clicked.connect(self.change_window)
self.window_2_button.clicked.connect(self.change_window)
def change_window(self):
if self.stack.currentIndex() == 0:
self.stack.setCurrentIndex(1)
else:
self.stack.setCurrentIndex(0)
if __name__ == "__main__":
app = QApplication(sys.argv)
M = Main()
sys.exit(app.exec())
Put your button outside your widgets (in your Main widget). The Ui class should manage the stacked layout.
For example:
class Ui(QWidget):
def setupUi(self, Main):
self.stack = QStackedLayout()
self.window_1 = QWidget()
self.window_2 = QWidget()
self.window_1_UI()
self.window_2_UI()
self.stack.addWidget(self.window_1)
self.stack.addWidget(self.window_2)
# Only one button
self.btn = QPushButton("Change window", self)
# Create the central widget of your Main Window
self.main_widget = QWidget()
layout = QVBoxLayout(self.main_widget)
layout.addLayout(self.stack)
layout.addWidget(self.btn)
self.setCentralWidget(self.main_widget)
self.btn.clicked.connect(self.change_window)
def change_window(self):
if self.stack.currentIndex() == 0:
self.stack.setCurrentIndex(1)
else:
self.stack.setCurrentIndex(0)
def window_1_UI(self):
label = QLabel("In Window 1", self.window_1)
def window_2_UI(self):
label = QLabel("In Window 2", self.window_2)
class Main(QMainWindow, Ui):
def __init__(self):
super(Main, self).__init__()
self.setupUi(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
M = Main()
M.show()
sys.exit(app.exec())
I am trying to show set of actions when a button is clicked and other set of options if another button is clicked.
Below is the code:
class Screen(QWidget):
def __init__(self):
super(Screen, self).__init__()
layout = QHBoxLayout(self)
self.all_running()
layout.addWidget(self.running_full_widget)
self.actions('1')
layout.addWidget(self.actions_full_widget)
self.setLayout(layout)
self.show()
def all_running(self):
self.running_full_widget = QWidget()
runnning_full_layout= QVBoxLayout()
button1 = QPushButton("btn1")
button2 = QPushButton("btn2")
button1.clicked.connect(lambda: self.actions('2'))
button2.clicked.connect(lambda: self.actions('3'))
runnning_full_layout.addWidget(button1)
runnning_full_layout.addWidget(button2)
self.running_full_widget.setLayout(runnning_full_layout)
def actions(self,value):
self.actions_full_widget= QWidget()
val = int(value)
print(val)
actions_layout = QVBoxLayout()
for i in range(val):
actions_item = QLabel(str(i))
actions_layout.addWidget(actions_item)
self.actions_full_widget.setLayout(actions_layout)
app = QApplication(sys.argv)
Gui = Screen()
sys.exit(app.exec_())
When button is clicked i can see the value is updated but it is not updated in the main layout.
how can i dynamically update the widgets ?
How can I do that in cases where i need to add widgets based on a dynamic value.
did i miss anything with signals and slots?
Kindly correct me if i am wrong. Thanks
Your code was almost there. The problem you are seeing is the widgets were being added but never removed. The following code could be simplified, but I tried to keep it close to yours so you could see the changes more easily.
The main change is now there is a class member screen_layout and the widgets are added/removed from it inside actions().
import sys
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget, QPushButton, QLabel, QApplication
class Screen(QWidget):
def __init__(self):
super(Screen, self).__init__()
layout = QHBoxLayout(self)
self.screen_layout = layout
self.all_running()
layout.addWidget(self.running_full_widget)
self.actions_full_widget = None
self.actions('1')
# layout.addWidget(self.actions_full_widget)
self.setLayout(layout)
self.show()
def all_running(self):
self.running_full_widget = QWidget()
runnning_full_layout= QVBoxLayout()
button1 = QPushButton("btn1")
button2 = QPushButton("btn2")
button1.clicked.connect(lambda: self.actions('2'))
button2.clicked.connect(lambda: self.actions('3'))
runnning_full_layout.addWidget(button1)
runnning_full_layout.addWidget(button2)
self.running_full_widget.setLayout(runnning_full_layout)
def actions(self,value):
# Remove any previously added widget
if self.actions_full_widget is not None:
self.screen_layout.removeWidget(self.actions_full_widget)
self.actions_full_widget.deleteLater()
self.actions_full_widget= QWidget()
val = int(value)
print(val)
actions_layout = QVBoxLayout()
for i in range(val):
actions_item = QLabel(str(i))
actions_layout.addWidget(actions_item)
self.actions_full_widget.setLayout(actions_layout)
self.screen_layout.addWidget(self.actions_full_widget)
app = QApplication(sys.argv)
Gui = Screen()
sys.exit(app.exec_())
I am pretty new at python but currently I am getting some problem here with the part where I am unable to get my stuff fit within the width of the window.
I am trying to set it in such a way that it is:
Eg. Name Button
by the way, I am using Maya to integrate and run my stuff.
If I set it to central, it fits but it is all over the place as I only wanted it to occupy a portion only. So are there any ways for me to fit it nicely into it?
By the way, if its possible, can it be done using my current codings?
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sip
import maya.OpenMayaUI as mui
import os
class MainWindow(QMainWindow):
def __init__(self, parent = None):
QMainWindow.__init__(self,parent)
self.resize(400,800)
self.setWindowTitle("GetShots")
self.pubDock = SetShotInfo()
self.pubDW = QDockWidget(self.tr(""), self)
self.pubDW.setWidget(self.pubDock)
# self.setCentralWidget(self.pubDW)
def getMayaWindow():
ptr = mui.MQtUtil.mainWindow()
return sip.wrapinstance(long(ptr), QObject)
def main():
global app
global form
app = qApp
form = MainWindow(getMayaWindow())
form.show()
class GetShot(QFrame):
def __init__(self, parent = None, display=None):
QFrame.__init__(self, parent)
self.createWidgets()
self.createLayout()
def createWidgets(self):
self.showLabel = QLabel('Show')
self.showName = QLineEdit()
self.showName.setText(str(os.environ['SHOW']))
self.shotLabel = QLabel('Shot Filter')
self.shotName = QLineEdit()
self.showButton = QPushButton('Set Show')
self.showButton.setMaximumWidth(200)
self.shotButton = QPushButton('Filter Shots')
self.shotButton.setMaximumWidth(200)
self.rootLabel = QLabel('Change Root')
self.rootButton = QComboBox()
def createLayout(self):
# Sets the Layout of Show and Shot
setShowLayout = QHBoxLayout()
setShowLayout.addWidget(self.showLabel)
setShowLayout.addWidget(self.showName)
setShowLayout.addWidget(self.showButton)
setShotLayout = QHBoxLayout()
setShotLayout.addWidget(self.shotLabel)
setShotLayout.addWidget(self.shotName)
setShotLayout.addWidget(self.shotButton)
# Sets the Change Root Layout
chgRootLayout = QHBoxLayout()
chgRootLayout.addWidget(self.rootLabel)
chgRootLayout.addWidget(self.rootButton)
mainLayout = QVBoxLayout()
mainLayout.addLayout(setShowLayout)
mainLayout.addLayout(setShotLayout)
mainLayout.addLayout(chgRootLayout)
self.setLayout(mainLayout)
if __name__ == '__main__':
main()
You need to use Layouts, combine vertical and horizontal and play with the size policy of the widgets to fit them as you need.
Here's a quick example:
import sys
from PyQt4 import QtCore, QtGui
class ButtonContainer(QtGui.QWidget):
def __init__(self):
super(ButtonContainer, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry( 150, 150, 650, 350)
btn = QtGui.QPushButton('Name button', self)
btn.setSizePolicy( QtGui.QSizePolicy( QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed ) )
vbox = QtGui.QVBoxLayout()
vbox.addWidget( btn )
self.setLayout(vbox)
self.show()
app = QtGui.QApplication(sys.argv)
ex = ButtonContainer()
sys.exit(app.exec_())
The commenters are right in suggesting QtDesigner, if you'd rather code it yourself at least have a mock up ui file where you can play interactively with the layouts and size policies, it's really helpful.