How to deal with layouts in PyQt4? - python

I want to display welcome label in middle of frame, how can I do that? It seems like layout problem as I googled but I haven't got final solution.
Here is the code:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Window(QMainWindow):
def __init__(self):
super(Window, self).__init__()
palette = QPalette()
palette.setBrush(QPalette.Background, QBrush(QPixmap("Login page.jpg")))
self.setPalette(palette)
self.setWindowTitle("Login Frame")
self.setWindowIcon(QIcon('logo.png'))
self.setGeometry(50, 50, 500, 300)
self.setFixedSize(500, 300)
self.addWidgets()
def addWidgets(self):
self.lblWelcome = QLabel("Welcome to Railway e-Ticketing System", self)
self.lblWelcome.move(100,30)
wcFont = QFont("Open Sans", 25)
self.lblWelcome.setFont(wcFont)
self.lblUid = QLabel("User ID:", self)
self.lblUid.move(100,80)
font = QFont("Open Sans", 10)
self.lneUid = QLineEdit(self)
self.lneUid.setFont(font)
self.lneUid.setFixedHeight(25)
self.lneUid.setFixedWidth(200)
self.lneUid.move(225, 80)
self.lblPass = QLabel("Password:", self)
self.lblPass.move(100, 130)
self.lnePass = QLineEdit(self)
self.lnePass.setEchoMode(QLineEdit.Password)
self.lnePass.setFixedHeight(25)
self.lnePass.setFixedWidth(200)
self.lnePass.move(225, 130)
self.lblInvalid = QLabel("",self)
self.lblInvalid.move(100, 180)
self.btnLogin = QPushButton("Login",self)
#btnLogin.resize(btnLogin.sizeHint())
self.btnLogin.move(175, 230)
self.btnLogin.clicked.connect(self.authenticate)
#self.authenticate()
self.btnReg = QPushButton("Register", self)
self.btnReg.move(300, 230)
#btnReg.clicked.connect(register)
self.show()
def authenticate(self):
uid = self.lneUid.text()
upass = self.lnePass.text()
if(len(uid.strip()) == 0 or len(upass.strip()) == 0):
palette = QPalette()
palette.setColor(QPalette.Foreground, Qt.darkRed)
self.lblInvalid.setPalette(palette)
self.lblInvalid.setText("*Invalid credentials .")
else:
self.lblInvalid.setText("")
def main():
app = QApplication(sys.argv)
LoginWin = Window()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
And here is the output:

You are using a QMainWindow which already has a layout with a central widget, a toolbar, a menu bar etc. The right way to use it is to define a central Widget, and put all your label and buttons in it. You didn't, so your label is not displayed properly.
But for your login frame, you clearly don't need all of this. You just need a QWidget:
import sys
from PyQt4 import QtCore,QtGui
class LoginFrame(QtGui.QWidget):
def __init__(self):
super(LoginFrame, self).__init__()
...
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
win = LoginFrame()
win.show()
sys.exit(app.exec_())
Your code should work with a QWidget, but I would still advise reading about box layout. Right now, you're using absolute positioning, which means you have to manually place your widget at a precise position, and you can't resize your window.
A box layout would be more flexible, and practical. For example you can use QFormLayout for the userID and password.
More about layouts on the ZetCode tutorial

Related

How to change the opacity of a PyQt5 window

I have just been experimenting with some animation in PyQt5 and am looking to animate the opacity of a window. I have had success with animating the opacity of buttons and QWidgets withink the window, however when I try to apply the same concept to the main QWidget class it doesn't seem to work. Below is my code for trying to get the animation to work on the window (I am aware this isn't the best looking code but I'm just trying to experiment, but also feel free to tell me about any big errors unrelated to the problem as well as I am also quite new to PyQt5):
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
class Test(QWidget):
def __init__(self):
super().__init__()
self.setStyleSheet("background: green")
self.setGeometry(100, 100, 400, 400)
self.b = QPushButton("Reduce", self, clicked=self.reduce)
self.b.show()
self.b.setStyleSheet("color: yellow")
self.show()
def reduce(self):
self.eff = QGraphicsOpacityEffect(self)
self.eff.setOpacity(1)
self.setGraphicsEffect(self.eff)
self.anim = QPropertyAnimation(self.eff, b"opacity")
self.anim.setDuration(500)
self.anim.setStartValue(1)
self.anim.setEndValue(0)
self.anim.start()
self.t = QTimer()
self.t.timeout.connect(self.loop)
self.t.start(10)
print(self.eff.opacity())
def loop(self):
self.update()
print(self.eff.opacity())
if self.anim.currentValue() == 0:
self.t.stop()
self.update()
if __name__ == "__main__":
window = QApplication(sys.argv)
app = Test()
window.exec_()
I thought maybe I am getting odd results as it isn't possible to do this when the widget is made to be the main widget in the window, however I also don't see why that would be a thing. What seems to happen for me is that the window does nothing and nothing changes, other than the button seems to half freeze, as in I am able to click it and get a result (run the function it is connected too) however no pressing down animation occurs as normally would. However, when I resize the window it will show a change, however this has to be manual as I added a basic loop to constantly resize and it did nothing. And finally when I resize the window, or change the opacity just by changing the opacity of self.eff it changes, but it just makes it all black even at values of 0.8, etc which is what leads me to believe it just isn't possible and some script is defaulting it to black, as the button will work fine while the rest goes black. Any help is appreciated.
Try like this:
import sys
from PyQt5.Qt import *
class Test(QWidget):
def __init__(self):
super().__init__()
self.setStyleSheet("background: green;")
self.resize(400, 400)
self.label = QLabel()
self.pixmap = QPixmap('Ok.png')
self.label.setPixmap(self.pixmap)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("background: #CD113B;")
self.b = QPushButton("Reduce", self, clicked=self.reduce)
self.b.setStyleSheet("background: blue; color: yellow;")
layout = QVBoxLayout(self)
layout.addWidget(self.label)
layout.addWidget(self.b)
def reduce(self):
self.anim = QPropertyAnimation(self, b"opacity")
self.anim.setDuration(3000)
self.anim.setLoopCount(3)
self.anim.setStartValue(0.0)
self.anim.setEndValue(1.0)
self.anim.start()
def windowOpacity(self):
return super().windowOpacity()
def setWindowOpacity(self, opacity):
super().setWindowOpacity(opacity)
opacity = pyqtProperty(float, windowOpacity, setWindowOpacity)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Test()
w.show()
sys.exit(app.exec_())
or so:
import sys
from PyQt5.Qt import *
class Test(QWidget):
def __init__(self):
super().__init__()
self.setStyleSheet("background: green;")
self.resize(400, 400)
self.label = QLabel()
self.pixmap = QPixmap('Ok.png')
self.label.setPixmap(self.pixmap)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("background: #CD113B;")
self.b = QPushButton("Reduce", self, clicked=self.reduce)
self.b.setStyleSheet("background: blue; color: yellow;")
layout = QVBoxLayout(self)
layout.addWidget(self.label)
layout.addWidget(self.b)
def reduce(self):
self.eff = QGraphicsOpacityEffect()
self.eff.setOpacity(1.0)
self.label.setGraphicsEffect(self.eff)
self.anim = QPropertyAnimation(self.eff, b"opacity")
self.anim.setDuration(3000)
self.anim.setLoopCount(3)
self.anim.setStartValue(0.0)
self.anim.setEndValue(1.0)
self.anim.start()
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Test()
w.show()
sys.exit(app.exec_())
Ok.png

Access A Variable from another class in PyQt5

In PyQt5, I've wrote a GUI. Basically, when a button is pressed, it open a new window, where choose an item from a list. What I want is that after you close the new window, the item you chose appears as text on the first window. It's a hard to explain.
This is the code:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5 import QtGui
class Add(QtWidgets.QMainWindow):
def __init__(self):
super(Add, self).__init__()
#Set The UI
self.initUI()
#Set The GUI Position And Size
self.setGeometry(1050, 500, 400, 50)
#Set The GUI Title
self.setWindowTitle("Add")
def initUI(self):
Central = QtWidgets.QWidget(self)
self.setCentralWidget(Central)
self.deckButton = QtWidgets.QPushButton(self)
self.deckButton.setText("Choose")
self.deckButton.clicked.connect(self.open_deck_browser)
hbox = QtWidgets.QHBoxLayout()
hbox.addWidget(self.deckButton, 1)
Central.setLayout(hbox)
def open_deck_browser(self):
self.w = SetDeck()
self.w.show()
class SetDeck(QtWidgets.QMainWindow):
def __init__(self):
super(SetDeck, self).__init__()
#Set The UI
self.initUI()
#Set The GUI Position And Size
self.setGeometry(200, 200, 800, 640)
#Set The GUI Title
self.setWindowTitle("Choose Deck")
def initUI(self):
widAddToDeckWindow = QtWidgets.QWidget(self)
self.setCentralWidget(widAddToDeckWindow)
#Create The List Widget
self.deckList = QtWidgets.QListWidget()
self.deckList.insertItem(0, "Hello")
self.deckList.insertItem(1, "Hi")
self.deckList.insertItem(2, "Hello There")
self.deckList.item(0).setSelected(True)
self.deckList.itemSelectionChanged.connect(self.show_List)
print([x.row() for x in self.deckList.selectedIndexes()])
#Create The Select Deck Button
self.selectDeck = QtWidgets.QPushButton(self)
self.selectDeck.setText("Choose")
hboxCreateBottomButtons = QtWidgets.QHBoxLayout()
hboxCreateBottomButtons.addStretch()
hboxCreateBottomButtons.addWidget(self.selectDeck)
#Create The Main VBox
vboxMain = QtWidgets.QVBoxLayout()
vboxMain.addWidget(self.deckList)
vboxMain.addLayout(hboxCreateBottomButtons)
widAddToDeckWindow.setLayout(vboxMain)
def show_List(self):
print(repr(self.deckList.selectedItems()[0].text()))
def window():
app = QtWidgets.QApplication(sys.argv)
win = Add()
win.show()
sys.exit(app.exec_())
window()
I've tried using global variables, but it didn't work.
First of all, I recommend you improve your style when naming variables as they make reading easier, for example that the class name are nouns and not a verb.
Getting to the bottom of the problem, never use (or try to use) global variables as they cause silent bugs if there is a better option and you don't understand how it works. In the case that you want a window where you ask the user to provide information on how to select an option that will then be used in the main window then it is advisable to use a QDialog. In the following example, this is done and the "Choose" button is linked to the accept slot so that it closes the window, and that information can be used to know that the "x" button of the window was not closed. Also I have created a property that has the selected text.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
self.setGeometry(1050, 500, 400, 50)
self.setWindowTitle("Add")
def initUI(self):
central = QtWidgets.QWidget(self)
self.setCentralWidget(central)
self.deckButton = QtWidgets.QPushButton()
self.deckButton.setText("Choose")
self.deckButton.clicked.connect(self.open_deck_browser)
box = QtWidgets.QVBoxLayout(central)
box.addWidget(self.deckButton)
self.label = QtWidgets.QLabel()
box.addWidget(self.label)
self.label.hide()
def open_deck_browser(self):
dialog = DeckDialog()
if dialog.exec_() == QtWidgets.QDialog.Accepted:
self.label.show()
self.label.setText(dialog.selected_text)
class DeckDialog(QtWidgets.QDialog):
def __init__(self):
super(DeckDialog, self).__init__()
self.initUI()
self.setGeometry(200, 200, 800, 640)
self.setWindowTitle("Choose Deck")
def initUI(self):
self.deckList = QtWidgets.QListWidget()
self.deckList.insertItem(0, "Hello")
self.deckList.insertItem(1, "Hi")
self.deckList.insertItem(2, "Hello There")
self.deckList.item(0).setSelected(True)
self.selectDeck = QtWidgets.QPushButton(self)
self.selectDeck.setText("Choose")
hboxCreateBottomButtons = QtWidgets.QHBoxLayout()
hboxCreateBottomButtons.addStretch()
hboxCreateBottomButtons.addWidget(self.selectDeck)
vboxMain = QtWidgets.QVBoxLayout(self)
vboxMain.addWidget(self.deckList)
vboxMain.addLayout(hboxCreateBottomButtons)
self.selectDeck.clicked.connect(self.accept)
#property
def selected_text(self):
items = self.deckList.selectedItems()
if items:
return items[0].text()
return ""
def main():
app = QtWidgets.QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

PyQt QVBoxLayout and missing widgets?

I am trying to set up a window that has a text input & a combo box. At the moment I just want to see the text & the selection displayed under the appropriate widget.
I have used QVBoxLayout() as I will be adding more stuff later & thought it would be a simple way of laying out the window.
Unfortunately only the combo box ever gets displayed. The code:
from PyQt4 import QtCore, QtGui
import sys
class Polyhedra(QtGui.QMainWindow):
def __init__(self):
super(Polyhedra, self).__init__()
self.initUI()
def initUI(self):
# Poly names
self.pNames = QtGui.QLabel(self)
polyNameInput = QtGui.QLineEdit(self)
# polyName entry
polyNameInput.textChanged[str].connect(self.onChanged)
# Polytype selection
self.defaultPolyType = QtGui.QLabel("Random polyhedra", self)
polyType = QtGui.QComboBox(self)
polyType.addItem("Random polyhedra")
polyType.addItem("Spheres")
polyType.addItem("Waterman polyhedra")
polyType.activated[str].connect(self.onActivated)
# Layout
vbox = QtGui.QVBoxLayout()
vbox.addWidget(polyNameInput)
vbox.addWidget(self.pNames)
vbox.addWidget(polyType)
vbox.addWidget(self.defaultPolyType)
vbox.addStretch()
# Set up window
self.setGeometry(500, 500, 300, 300)
self.setWindowTitle('Pyticle')
self.show()
# Combo box
def onActivated(self, text):
self.defaultPolyType.setText(text)
self.defaultPolyType.adjustSize()
# Poly names
def onChanged(self, text):
self.pNames.setText(text)
self.pNames.adjustSize()
def main():
app = QtGui.QApplication(sys.argv)
ex = Polyhedra()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
So whats going on here? Am I missing some important directive to QVBoxLayout()?
Using Python 2.7 on Win 7 x64 machine with PyQt 4.
EDIT: Additional problem (still related to missing widgets)
I have amended the code following the clarification below. I then added more widgets when a certain option in the combobox is chosen (see below) but these widgets dont show. I attempted to add a child widget to 'widget' called 'ranPolyWidget' to take a numerical input.
# Combo box
def onActivated(self, text):
if text=="Random polyhedra":
self.randomSeedLbl = QtGui.QLabel("Seed: ", self)
randomSeed = QtGui.QLineEdit(self)
randomSeed.textChanged[str].connect(self.setSeed)
ranPolyWidget = QtGui.QWidget(self.widget)
rbox = QtGui.QVBoxLayout(ranPolyWidget)
rbox.addWidget(randomSeed)
self.layout().addWidget(ranPolyWidget)
self.show()
else:
self.defaultPolyType.setText(text)
self.defaultPolyType.adjustSize()
Same issue as before, no widgets. I am missing something pretty fundamental arent I?
You're forgetting to set it to the widget or main window, so since the QComboBox is the last one made, it's the only one displayed. Basically, everything is added to the layout, but the layout is "free-floating", and so it does not display properly. You need to bind the layout to a QWidget, which I do here. For most widgets, you can can do this by the QtGui.QVBoxLayout(widget) or by widget.setLayout(layout).
Alternatively, if you want multiple layouts on a widget, you can do have a parent layout and then add each child layout to the main layout.
EDIT: This is a better answer:
Make a widget, set layout to widget and set as central widget.
QMainWindow-s don't like you using the builtin layout or overriding it.
widget = QtGui.QWidget()
vbox = QtGui.QVBoxLayout(widget)
self.setCentralWidget(widget)
Old Answer:
self.layout().addLayout(vbox).
This should fix your issue:
Changes I made:
Since QMainWindow already has a layout, add in a widget (28G) and then set the VBoxLayout to the widget and add it to the main window.
from PyQt4 import QtCore, QtGui
import sys
class Polyhedra(QtGui.QMainWindow):
def __init__(self):
super(Polyhedra, self).__init__()
self.initUI()
def initUI(self):
# Poly names
self.pNames = QtGui.QLabel(self)
polyNameInput = QtGui.QLineEdit(self)
# polyName entry
polyNameInput.textChanged[str].connect(self.onChanged)
# Polytype selection
self.defaultPolyType = QtGui.QLabel("Random polyhedra", self)
polyType = QtGui.QComboBox(self)
polyType.addItem("Random polyhedra")
polyType.addItem("Spheres")
polyType.addItem("Waterman polyhedra")
polyType.activated[str].connect(self.onActivated)
# Layout
widget = QtGui.QWidget()
vbox = QtGui.QVBoxLayout(widget)
vbox.addWidget(polyNameInput)
vbox.addWidget(self.pNames)
vbox.addWidget(polyType)
vbox.addWidget(self.defaultPolyType)
vbox.addStretch()
# Set up window
self.setGeometry(500, 500, 300, 300)
self.setWindowTitle('Pyticle')
self.layout().addWidget(widget)
self.show()
# Combo box
def onActivated(self, text):
self.defaultPolyType.setText(text)
self.defaultPolyType.adjustSize()
# Poly names
def onChanged(self, text):
self.pNames.setText(text)
self.pNames.adjustSize()
def main():
app = QtGui.QApplication(sys.argv)
ex = Polyhedra()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
EDIT:
For adding new widgets, you should add them to the layout of the central widget and parent them to that widget.
Here's how I'd restructure your full code:
from PyQt4 import QtCore, QtGui
import sys
class CentralWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(CentralWidget, self).__init__(parent)
# set layouts
self.layout = QtGui.QVBoxLayout(self)
# Poly names
self.pNames = QtGui.QLabel(self)
polyNameInput = QtGui.QLineEdit(self)
# polyName entry
polyNameInput.textChanged[str].connect(self.onChanged)
# Polytype selection
self.defaultPolyType = QtGui.QLabel("Random polyhedra", self)
polyType = QtGui.QComboBox(self)
polyType.addItem("Random polyhedra")
polyType.addItem("Spheres")
polyType.addItem("Waterman polyhedra")
polyType.activated[str].connect(self.onActivated)
self.layout.addWidget(polyNameInput)
self.layout.addWidget(self.pNames)
self.layout.addWidget(polyType)
self.layout.addWidget(self.defaultPolyType)
self.layout.addStretch()
def onActivated(self, text):
'''Adds randSeed to layout'''
if text=="Random polyhedra":
self.randomSeedLbl = QtGui.QLabel("Seed: ", self)
randomSeed = QtGui.QLineEdit(self)
randomSeed.textChanged[str].connect(self.setSeed)
self.layout.addWidget(randomSeed)
else:
self.defaultPolyType.setText(text)
self.defaultPolyType.adjustSize()
# Poly names
def onChanged(self, text):
self.pNames.setText(text)
self.pNames.adjustSize()
class Polyhedra(QtGui.QMainWindow):
def __init__(self):
super(Polyhedra, self).__init__()
# I like having class attributes bound in __init__
# Not very Qt of me, but it's more
# so I break everything down into subclasses
# find it more Pythonic and easier to debug: parent->child
# is easy when I need to repaint or delete child widgets
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):
'''Pass to child'''
self.central_widget.onActivated(text)
def main():
app = QtGui.QApplication(sys.argv)
ex = Polyhedra()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

How to resize the main window again after setFixedSize()?

I would like to resize the MainWindow (QMainWindow) after I make some widgets unvisible and vice versa. And I want to block the window resize.
def hideAndShowWidget(self):
self.widgetObject.setVisible(not self.widgetObject.isVisible() )
# change main window size here
# ...
self.setFixedSize(self.width(), self.height())
My problem is, that i can not change the window size after i call setFixedSize() first time. I read here that I must use QWIDGETSIZE_MAX() to remove constraints, but I don't know how can I use it, I get the error:
NameError: name 'QWIDGETSIZE_MAX' is not defined
I think you have the mechanism more or less right. You just have to make sure the height calculation is done correctly (i.e. before the visibility of the widget changes).
The following example works correctly for me (only tested on Linux, though):
from PySide import QtGui
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.widgetObject = QtGui.QTextEdit(self)
self.button = QtGui.QPushButton('Hide Widget', self)
self.button.clicked.connect(self.hideAndShowWidget)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.button)
layout.addWidget(self.widgetObject)
self.setFixedSize(300, 200)
def hideAndShowWidget(self):
height = self.height()
if self.widgetObject.isVisible():
height -= self.widgetObject.height()
self.widgetObject.setVisible(False)
self.button.setText('Show Widget')
else:
height += self.widgetObject.height()
self.widgetObject.setVisible(True)
self.button.setText('Hide Widget')
self.setFixedSize(self.width(), height)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Use the sizeHint(). It contains the size the widget would like to have. Set the fixed size exactly to the size hint.
Working example:
from PySide import QtGui
class Window(QtGui.QMainWindow):
def __init__(self):
super().__init__()
self.setFixedSize(400, 300)
widget = QtGui.QWidget()
layout = QtGui.QVBoxLayout(widget)
button = QtGui.QPushButton('Toggle visibility')
button.clicked.connect(self.hideAndShowWidget)
layout.addWidget(button)
self.widgetObject = QtGui.QLabel('Test')
layout.addWidget(self.widgetObject)
self.setCentralWidget(widget)
def hideAndShowWidget(self):
self.widgetObject.setVisible(not self.widgetObject.isVisible() )
# change main window size
self.setFixedSize(self.sizeHint())
app = QtGui.QApplication([])
w = Window()
w.show()
app.exec_()

How to fit widgets within frame in python

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.

Categories

Resources