I am using QGridLayout in my project, and the code is:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent=parent)
widget = QWidget()
self.setCentralWidget(widget)
layout = QGridLayout()
widget.setLayout(layout)
lay1 = QVBoxLayout()
lay1Header = QHBoxLayout()
lay1Header.addWidget(QLabel('lay1'))
lay1.addLayout(lay1Header)
label1 = QLabel('label1')
label1.setStyleSheet('background: rgb(255, 0, 0)')
lay1.addWidget(label1)
lay2 = QVBoxLayout()
lay2Header = QHBoxLayout()
lay2Header.addWidget(QLabel('lay2'))
lay2Header.addWidget(QLineEdit())
lay2.addLayout(lay2Header)
label2 = QLabel('label2')
label2.setStyleSheet('background: rgb(0, 0, 255)')
lay2.addWidget(label2)
layout.addLayout(lay1, 0, 0, 1, 1)
layout.addLayout(lay2, 0, 1, 1, 1)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
And the result is:
My environment is:
win 10
anaconda
pyqt5 5.14.0
How can I make the size of label1/label2 the same?
The size of the items in a QGridLayout depends on all the items in the column or row, not just one of them. So for this case the solution is to set the same alignment factor for the columns and set the height of the first QLabel to be that of the QLineEdit:
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent=parent)
widget = QWidget()
self.setCentralWidget(widget)
layout = QGridLayout(widget)
lbl1 = QLabel("lay1")
lay1 = QVBoxLayout()
lay1Header = QHBoxLayout()
lay1Header.addWidget(lbl1)
lay1.addLayout(lay1Header)
label1 = QLabel("label1")
label1.setStyleSheet("background: rgb(255, 0, 0)")
lay1.addWidget(label1)
le1 = QLineEdit()
lay2 = QVBoxLayout()
lay2Header = QHBoxLayout()
lay2Header.addWidget(QLabel("lay2"))
lay2Header.addWidget(le1)
lay2.addLayout(lay2Header)
label2 = QLabel("label2")
label2.setStyleSheet("background: rgb(0, 0, 255)")
lay2.addWidget(label2)
layout.addLayout(lay1, 0, 0, 1, 1)
layout.addLayout(lay2, 0, 1, 1, 1)
layout.setColumnStretch(0, 1)
layout.setColumnStretch(1, 1)
lbl1.setFixedHeight(le1.sizeHint().height())
Related
I'm trying to get a lineEdit that have a cursor in it when a button is clicked. For example: I run application, put a cursor in one lineEdit, and when clicking a button - some text should be set in chosen lineEdit.
I've tried with keyboardGrabber, but it returns button =None.
import sys
from PyQt5 import QtWidgets, QtCore
class Mainwindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("window")
self.lineEdit1 = QtWidgets.QLineEdit()
self.lineEdit2 = QtWidgets.QLineEdit()
self.lineEdit3 = QtWidgets.QLineEdit()
self.pushButton = QtWidgets.QPushButton()
self.label = QtWidgets.QLabel()
self.label.setText('#1')
self.frame = QtWidgets.QFrame(self)
self.frame.setGeometry(QtCore.QRect(0, 0, 200, 100))
self.gridLayout = QtWidgets.QGridLayout(self.frame)
self.gridLayout.addWidget(self.lineEdit1, 0, 0, 1, 1)
self.gridLayout.addWidget(self.lineEdit2, 0, 1, 1, 1)
self.gridLayout.addWidget(self.lineEdit3, 0, 2, 1, 1)
self.gridLayout.addWidget(self.label, 0, 3, 1, 1)
self.gridLayout.addWidget(self.pushButton, 1, 0, 1, 1)
self.pushButton.clicked.connect(self.function)
def function(self):
widget = self.keyboardGrabber()
widget.setText('some text')
if __name__ == '__main__':
app = QtWidgets.QApplication([])
application = Mainwindow()
application.show()
Try it: void QApplication::focusChanged(QWidget *old, QWidget *now)
This signal is emitted when the widget that has keyboard focus changed from old to now, i.e., because the user pressed the tab-key, clicked into a widget or changed the active window. Both old and now can be nullptr.
import sys
from PyQt5 import QtWidgets, QtCore
class Mainwindow(QtWidgets.QMainWindow): # QMainWindow QWidget
def __init__(self):
super().__init__()
QtWidgets.qApp.focusChanged.connect(self.on_focusChanged) # +++
self.setWindowTitle("window")
self.lineEdit1 = QtWidgets.QLineEdit(self)
self.lineEdit1.setFocus() # +
self.lineEdit2 = QtWidgets.QLineEdit()
self.lineEdit3 = QtWidgets.QLineEdit()
self.pushButton = QtWidgets.QPushButton()
self.label = QtWidgets.QLabel()
self.label.setText('#1')
self.frame = QtWidgets.QFrame(self)
self.setCentralWidget(self.frame) # +
self.frame.setGeometry(QtCore.QRect(0, 0, 200, 100))
self.gridLayout = QtWidgets.QGridLayout(self.frame)
self.gridLayout.addWidget(self.lineEdit1, 0, 0, 1, 1)
self.gridLayout.addWidget(self.lineEdit2, 0, 1, 1, 1)
self.gridLayout.addWidget(self.lineEdit3, 0, 2, 1, 1)
self.gridLayout.addWidget(self.label, 0, 3, 1, 1)
self.gridLayout.addWidget(self.pushButton, 1, 0, 1, 1)
self.lineFocus = ... # +++
self.pushButton.clicked.connect(self.function)
def function(self):
# widget = self.keyboardGrabber()
# widget.setText('some text')
self.lineFocus.setText('some text')
#QtCore.pyqtSlot("QWidget*", "QWidget*")
def on_focusChanged(self, old, now): # +++
#print(f"\nold: {old}, now: {now}")
self.lineFocus = old
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
application = Mainwindow()
application.show()
sys.exit(app.exec_())
Here is MCVE ( A Minimal, Complete, verifiable example ) should run right off the bat
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QFormLayout, QGroupBox,QPushButton, QScrollArea
class Window(QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setWindowTitle('MCVE')
'''Window Background'''
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.black)
self.setPalette(p)
'''Core Layouts'''
self.mainLayout = QGridLayout()
self.picLayout = QHBoxLayout()
self.redditSubs = QVBoxLayout()
self.downloadBar = QHBoxLayout()
self.panel = QWidget()
self.profileInfo = QGridLayout()
'''redditSubs Layout -----------------------------------------------------'''
self.formLayout = QFormLayout()
self.groupBox = QGroupBox()
labelList = []
favList = []
favIcon = QPushButton('Favs')
favIcon.setToolTip('<i><b>Add to favourites</i></b>')
subscribedList = ['AccidentalRenaissance', 'HadToHurt', 'WidescreenWallpaper', 'iamverybadass',
'LivestreamFail', 'CatastrophicFailure', 'KidsAreFuckingStupid', 'therewasanattempt',
'BetterEveryLoop', 'madlads', 'IdiotsInCars', 'youseeingthisshit', 'blackmagicfuckery',
'WatchPeopleDieInside', 'SequelMemes', 'iamatotalpieceofshit', 'cleavesdropping',
'PewdiepieSubmissions', 'technicallythetruth', 'KeanuBeingAwesome', 'science', 'TikTokCringe',
'Cringetopia']
for i in range(len(subscribedList)):
labelList.append(QLabel('r/' + subscribedList[i]))
favList.append(favIcon)
self.formLayout.addRow(labelList[i], favList[i])
self.groupBox.setLayout(self.formLayout)
scroll = QScrollArea()
scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll.setWidget(self.groupBox)
scroll.setWidgetResizable(True)
self.redditSubs.addWidget(scroll)
self.groupBox.setObjectName('backgroundColor')
self.groupBox.setStyleSheet('QLabel {color: #707070; font-size: 20px; padding-left: 10px; padding-top: 15px;}'
'QGroupBox#backgroundColor {background-color: rgb(20, 21, 24); border: 1px solid black}'
'QPushButton {text-align:center; font-size: 20px; padding-left: 10px; padding-top: 15px;}')
'''------------------------------------------------------'''
'''Nested Layout'''
self.mainLayout.addLayout(self.profileInfo, 0, 0)
self.mainLayout.addLayout(self.picLayout, 0, 1)
self.mainLayout.addLayout(self.redditSubs, 1, 0)
self.mainLayout.addLayout(self.downloadBar, 1, 1)
'''Widgets'''
self.display = QLabel('QHBoxLayout()')
self.download = QLabel('QHBoxLayout()')
self.subs = QLabel('QVBoxLayout()')
self.fileInfo = QLabel('QGridLayout()')
'''AddWidgets'''
self.picLayout.addWidget(self.display)
self.downloadBar.addWidget(self.download)
self.redditSubs.addWidget(self.subs)
self.mainLayout.addWidget(self.panel, 0, 0)
self.profileInfo.addWidget(self.fileInfo, 0, 0)
'''Stylesheet'''
self.panel.setStyleSheet("background-color: red;")
self.display.setStyleSheet('QLabel {color: white;}')
self.download.setStyleSheet('QLabel {color: white;}')
'''Initiating mainLayout '''
self.window = QWidget()
self.window.setLayout(self.mainLayout)
self.setCentralWidget(self.window)
if __name__ == '__main__':
app = QApplication([])
w = Window()
w.showMaximized()
app.exec_()
Issues:
Labels are getting added one after the other but not the buttons. I did favList.append(QPushButton('Favs')) which works fine but this way I cannot add icons.
Unable to resize buttons
Can't seem to remove the border around the formLayout.
Added : BEFORE/AFTER PIC
Added code:
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QPushButton, QScrollArea
class Window(QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setWindowTitle("MCVE")
"""Window Background"""
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.darkYellow)
self.setPalette(p)
"""Core Layouts"""
self.mainLayout = QGridLayout()
self.picLayout = QHBoxLayout()
self.redditSubs = QVBoxLayout()
self.downloadBar = QHBoxLayout()
self.profileInfo = QGridLayout()
"""Nested Layout"""
self.mainLayout.addLayout(self.profileInfo, 0, 0)
self.mainLayout.addLayout(self.picLayout, 0, 1)
self.mainLayout.addLayout(self.redditSubs, 1, 0)
self.mainLayout.addLayout(self.downloadBar, 1, 1)
"""Widgets"""
self.display = QLabel("QHBoxLayout()")
self.download = QLabel("QHBoxLayout()")
self.subs = QLabel("QVBoxLayout()")
self.fileInfo = QLabel("QGridLayout()")
self.panel = QWidget()
self.redditWidget = QWidget()
'''redditSubs Layout -----------------------------------------------------'''
lay1 = QVBoxLayout()
self.redditWidget.setLayout(lay1)
subscribedList = ['AccidentalRenaissance', 'HadToHurt', 'WidescreenWallpaper', 'iamverybadass',
'LivestreamFail', 'CatastrophicFailure', 'KidsAreFuckingStupid', 'therewasanattempt',
'BetterEveryLoop', 'madlads', 'IdiotsInCars', 'youseeingthisshit', 'blackmagicfuckery',
'WatchPeopleDieInside', 'SequelMemes', 'iamatotalpieceofshit', 'cleavesdropping',
'PewdiepieSubmissions', 'technicallythetruth', 'KeanuBeingAwesome', 'science', 'TikTokCringe',
'Cringetopia']
for i in range(len(subscribedList)):
lay1.addWidget(QLabel('/r' + subscribedList[i]))
favIcon = QPushButton('Favs')
favIcon.setFixedSize(40, 40)
lay1.addWidget(favIcon, alignment=Qt.AlignRight)
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setWidget(self.redditWidget)
lay1.addWidget(scroll) ##
self.redditWidget.setObjectName('backgroundColor')
self.redditWidget.setStyleSheet('QLabel {color: #707070; font-size: 15px;}'
'QWidget#backgroundColor {background-color: rgb(20, 21, 24)};'
'QPushButton {text-align:center; font-size: 15px;}')
self.redditSubs.addWidget(self.redditWidget)
'''------------------------------------------------------'''
"""AddWidgets"""
self.picLayout.addWidget(self.display)
self.downloadBar.addWidget(self.download)
self.profileInfo.addWidget(self.panel)
lay = QVBoxLayout(self.panel)
lay.addWidget(self.fileInfo)
"""Stylesheet"""
self.panel.setStyleSheet("background-color: red;")
"""Initiating mainLayout """
self.window = QWidget()
self.window.setLayout(self.mainLayout)
self.setCentralWidget(self.window)
if __name__ == "__main__":
app = QApplication([])
w = Window()
w.showMaximized()
app.exec_()
Buttons are not on the same level as Labels, and Scroll bar isn't working and showing up. '##' when commented only then it runs.
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QPushButton, QScrollArea
class Window(QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setWindowTitle("MCVE")
"""Window Background"""
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.darkYellow)
self.setPalette(p)
"""Core Layouts"""
self.mainLayout = QGridLayout()
self.picLayout = QHBoxLayout()
self.redditSubs = QVBoxLayout()
self.downloadBar = QHBoxLayout()
self.profileInfo = QGridLayout()
"""Nested Layout"""
self.mainLayout.addLayout(self.profileInfo, 0, 0)
self.mainLayout.addLayout(self.picLayout, 0, 1)
self.mainLayout.addLayout(self.redditSubs, 1, 0)
self.mainLayout.addLayout(self.downloadBar, 1, 1)
"""Widgets"""
self.display = QLabel("QHBoxLayout()")
self.download = QLabel("QHBoxLayout()")
self.subs = QLabel("QVBoxLayout()")
self.fileInfo = QLabel("QGridLayout()")
self.panel = QWidget()
self.redditWidget = QWidget()
'''redditSubs Layout -----------------------------------------------------'''
lay1 = QGridLayout()
self.redditWidget.setLayout(lay1)
subscribedList = ['AccidentalRenaissance', 'HadToHurt', 'WidescreenWallpaper', 'iamverybadass',
'LivestreamFail', 'CatastrophicFailure', 'KidsAreFuckingStupid', 'therewasanattempt',
'BetterEveryLoop', 'madlads', 'IdiotsInCars', 'youseeingthisshit', 'blackmagicfuckery',
'WatchPeopleDieInside', 'SequelMemes', 'iamatotalpieceofshit', 'cleavesdropping',
'PewdiepieSubmissions', 'technicallythetruth', 'KeanuBeingAwesome', 'science', 'TikTokCringe',
'Cringetopia']
for i in range(len(subscribedList)):
lay1.addWidget(QLabel('/r' + subscribedList[i]),i,0)
favIcon = QPushButton('Favs')
favIcon.setFixedSize(40, 40)
lay1.addWidget(favIcon, i,1)
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setWidget(self.redditWidget)
# lay1.addWidget(scroll)
self.redditWidget.setObjectName('backgroundColor')
self.redditWidget.setStyleSheet('QLabel {color: #707070; font-size: 15px;}'
'QWidget#backgroundColor {background-color: rgb(20, 21, 24)};'
'QPushButton {text-align:center; font-size: 15px;}')
self.redditSubs.addWidget(scroll)
'''------------------------------------------------------'''
"""AddWidgets"""
self.picLayout.addWidget(self.display)
self.downloadBar.addWidget(self.download)
self.profileInfo.addWidget(self.panel)
lay = QVBoxLayout(self.panel)
lay.addWidget(self.fileInfo)
"""Stylesheet"""
self.panel.setStyleSheet("background-color: red;")
"""Initiating mainLayout """
self.window = QWidget()
self.window.setLayout(self.mainLayout)
self.setCentralWidget(self.window)
if __name__ == "__main__":
app = QApplication([])
w = Window()
w.showMaximized()
app.exec_()
Just the way I wanted.
Layout structure:
self.mainLayout = QGridLayout()
self.subLayout1 = QGridLayout()
self.subLayout2 = QVBoxLayout()
...
...
...
self.mainLayout.addLayout(subLayout1,0,0)
I have tried:
self.mainLayout = QGridLayout()
self.panel = QWidget()
self.subLayout1 = QGridLayout(self.panel)
self.mainLayout.addLayout(subLayout1,0,0)
self.panel.setStylesheet("background-color: red;")
Error: QLayout::addChildLayout: layout "" already has a parent
This is how I have set my mainLayout color
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.black)
self.setPalette(p)
which needs on back when showing subLayout1, subLayout2 etc
How do I do that ?
Edit : Added MCVE ( A Minimal, Complete, verifiable example )
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
class Window(QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setWindowTitle('MCVE')
'''Window Background'''
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.darkYellow)
self.setPalette(p)
'''Core Layouts'''
self.mainLayout = QGridLayout()
self.picLayout = QHBoxLayout()
self.redditSubs = QVBoxLayout()
self.downloadBar = QHBoxLayout()
self.panel = QWidget()
self.profileInfo = QGridLayout(self.panel)
'''Nested Layout'''
self.mainLayout.addLayout(self.profileInfo, 0, 0)
self.mainLayout.addLayout(self.picLayout, 0, 1)
self.mainLayout.addLayout(self.redditSubs, 1, 0)
self.mainLayout.addLayout(self.downloadBar, 1, 1)
'''Widgets'''
self.display = QLabel('QHBoxLayout()')
self.download = QLabel('QHBoxLayout()')
self.subs = QLabel('QVBoxLayout()')
self.fileInfo = QLabel('QGridLayout()')
'''AddWidgets'''
self.picLayout.addWidget(self.display)
self.downloadBar.addWidget(self.download)
self.redditSubs.addWidget(self.subs)
self.profileInfo.addWidget(self.fileInfo, 0, 0)
'''Stylesheet'''
self.panel.setStyleSheet("background-color: red;")
'''Initiating mainLayout '''
self.window = QWidget()
self.window.setLayout(self.mainLayout)
self.setCentralWidget(self.window)
if __name__ == '__main__':
app = QApplication([])
w = Window()
w.showNormal()
app.exec_()
As said above, the code error QLayout::addChildLayout: layout "" already has a parent, if Stylesheet section is commented out, QGridLayout() label shows up on top of that darkyellow background and I want that background section to be red.
A QXLayout is not a visual element but a class that controls the position and especially the size of the widget that is assigned. So wanting to set a color to that class that is not a visual element makes no sense.
On the other hand, the error is caused because the 2 following codes are equivalent:
x = QXLayout(w)
x = QXLayout()
w.setLayout(x)
In your case you have indicated that the layout "profileInfo" belongs to "panel" with the following code: self.profileInfo = QGridLayout(self.panel), but then you indicate that the same layout belongs to "mainLayout" through the following code: self.mainLayout.addLayout(self.profileInfo, 0, 0). So to avoid the warning you must pass replace the last code with self.mainLayout.addWidget(self.panel, 0, 0).
Update:
If you want a widget to be inside another one then it must be a child of the second one, so the "fileInfo" must be a child of "panel", but since you want it to occupy the entire size of the parent then you must use a layout.
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
class Window(QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setWindowTitle("MCVE")
"""Window Background"""
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.darkYellow)
self.setPalette(p)
"""Core Layouts"""
self.mainLayout = QGridLayout()
self.picLayout = QHBoxLayout()
self.redditSubs = QVBoxLayout()
self.downloadBar = QHBoxLayout()
self.profileInfo = QGridLayout()
"""Nested Layout"""
self.mainLayout.addLayout(self.profileInfo, 0, 0)
self.mainLayout.addLayout(self.picLayout, 0, 1)
self.mainLayout.addLayout(self.redditSubs, 1, 0)
self.mainLayout.addLayout(self.downloadBar, 1, 1)
"""Widgets"""
self.display = QLabel("QHBoxLayout()")
self.download = QLabel("QHBoxLayout()")
self.subs = QLabel("QVBoxLayout()")
self.fileInfo = QLabel("QGridLayout()")
self.panel = QWidget()
"""AddWidgets"""
self.picLayout.addWidget(self.display)
self.downloadBar.addWidget(self.download)
self.redditSubs.addWidget(self.subs)
self.profileInfo.addWidget(self.panel, 0, 0)
lay = QVBoxLayout(self.panel)
lay.addWidget(self.fileInfo)
"""Stylesheet"""
self.panel.setStyleSheet("background-color: red;")
"""Initiating mainLayout """
self.window = QWidget()
self.window.setLayout(self.mainLayout)
self.setCentralWidget(self.window)
if __name__ == "__main__":
app = QApplication([])
w = Window()
w.showNormal()
app.exec_()
I am trying to build a simple GUI with PyQt5, where I have a few widgets which I want to align using QGridLayout.
Look at the following example code which I found on some website:
import sys
from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit,
QTextEdit, QGridLayout, QApplication)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
title = QLabel('Title')
author = QLabel('Author')
review = QLabel('Review')
titleEdit = QLineEdit()
authorEdit = QLineEdit()
reviewEdit = QTextEdit()
grid = QGridLayout()
grid.setSpacing(10)
grid.addWidget(title, 1, 0)
grid.addWidget(titleEdit, 1, 1)
grid.addWidget(author, 2, 0)
grid.addWidget(authorEdit, 2, 1)
grid.addWidget(review, 3, 0)
grid.addWidget(reviewEdit, 3, 1, 5, 1)
self.setLayout(grid)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('Review')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Output
As you can see, there are three labels in the first column, each spanning one cell vertically and one cell horizontally.
In the second column there are two 1x1 widgets and one 5x1 widget.
Let's say I want to place another label called test and a lineedit called testEdit below.
Naively I would modify initUI() like this:
def initUI(self):
title = QLabel('Title')
author = QLabel('Author')
review = QLabel('Review')
test = QLabel('Test')
titleEdit = QLineEdit()
authorEdit = QLineEdit()
reviewEdit = QTextEdit()
testEdit = QTextEdit()
grid = QGridLayout()
grid.setSpacing(10)
grid.addWidget(title, 1, 0)
grid.addWidget(titleEdit, 1, 1)
grid.addWidget(author, 2, 0)
grid.addWidget(authorEdit, 2, 1)
grid.addWidget(review, 3, 0)
grid.addWidget(reviewEdit, 3, 1, 5, 1)
grid.addWidget(test, 8, 0)
grid.addWidget(testEdit, 8, 1)
self.setLayout(grid)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('Review')
self.show()
Where I just placed the new 1x1 widgets in the 8th row, below the previous one, which produces:
Output 2
However the result is not what I would expect, since the testEdit-widget is definitely not of size 1x1 and the reviewEdit-widget is also altered.
So why doesn't it work this way?
Try it:
import sys
from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit,
QTextEdit, QGridLayout, QApplication,
)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
title = QLabel('Title')
author = QLabel('Author')
review = QLabel('Review')
test = QLabel('Test')
titleEdit = QLineEdit()
authorEdit = QLineEdit()
reviewEdit = QTextEdit()
testEdit = QTextEdit()
testEdit.setMaximumHeight(20) # +++
grid = QGridLayout()
grid.setSpacing(10)
grid.addWidget(title, 1, 0)
grid.addWidget(titleEdit, 1, 1)
grid.addWidget(author, 2, 0)
grid.addWidget(authorEdit, 2, 1)
grid.addWidget(review, 3, 0)
grid.addWidget(reviewEdit, 3, 1, 5, 1)
grid.addWidget(test, 8, 0)
grid.addWidget(testEdit, 8, 1)
self.setLayout(grid)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('Review')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
I am trying to create a simple application with PySide, but it seems that I didn't read the docs properly. That is my code:
from PySide.QtGui import *
from PySide.QtCore import Qt
class Window(QMainWindow):
def __init__(self, parent = None):
QMainWindow.__init__(self, parent)
self.scene = QGraphicsScene()
self.view1 = QGraphicsView(self.scene, self)
self.view2 = QGraphicsView(self.scene, self)
self.gridLayout = QGridLayout()
self.gridLayout.addWidget(self.view1, 0, 0, Qt.AlignLeft)
self.gridLayout.addWidget(self.view2, 0, 1, Qt.AlignRight)
self.gridLayout.setColumnMinimumWidth(0, 300)
self.gridLayout.setColumnMinimumWidth(1, 300)
self.setLayout(self.gridLayout)
self.view1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.view2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.scene.addLine(0, 0, 1000, 1000)
if __name__ == "__main__":
app = QApplication(())
window = Window()
window.showMaximized()
app.exec_()
The code executes, but it should display a window with two QGraphicsViews, which should divide the window in half, but I only get one QGraphicsView in its minimum size. Can someone help me with this?
Thanks in advance.
You need to create a central widget for a QMainWindow, and then set the layout on that. Simplifying your example:
from PySide.QtGui import *
class Window(QMainWindow):
def __init__(self, parent = None):
QMainWindow.__init__(self, parent)
self.scene = QGraphicsScene()
self.view1 = QGraphicsView(self.scene, self)
self.view2 = QGraphicsView(self.scene, self)
self.view1.setFrameShape(QFrame.NoFrame)
self.view2.setFrameShape(QFrame.NoFrame)
widget = QWidget(self)
layout = QGridLayout(widget)
layout.addWidget(self.view1, 0, 0)
layout.addWidget(self.view2, 0, 1)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setCentralWidget(widget)
self.scene.addLine(0, 0, 1000, 1000)
if __name__ == "__main__":
app = QApplication(())
window = Window()
window.showMaximized()
app.exec_()