I'm using pyqt for the first time and I am trying to figure out how to get the text "example.py" in my Qlabel to align vertically. In this code I have set the Qlabel to a fixed height of 35, but the text is not sitting center between the top of the window and the top of the splitter below it.
If I set the fixed height of the Qlabel to 20, that gets a little closer to things looking vertically aligned (but not totally) but also introduces the problem of some of the bottom of the test "example.py" getting cut off.
Maybe it has something to do with some margin or something above the splitter section... Makes me think that it could be the case and that's why the text is getting cut off at the bottom. In either case I am not sure how to address the issue.
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os, sys
from PyQt5.QtWidgets import (QApplication, QWidget, QFrame, QSplitter, QStyleFactory,
QHBoxLayout, QVBoxLayout, QLabel)
from PyQt5.QtCore import Qt
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
#self.showFullScreen()
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
topbar = QLabel("example.py", self)
topbar.setAlignment(Qt.AlignVCenter)
topbar.setIndent(20)
topbar.setFixedHeight(35)
layout.addWidget(topbar)
v_left = QFrame(self)
v_left.setFrameShape(QFrame.StyledPanel)
v_middle = QFrame(self)
v_middle.setFrameShape(QFrame.StyledPanel)
v_right = QFrame(self)
v_right.setFrameShape(QFrame.StyledPanel)
splitter = QSplitter(Qt.Horizontal)
splitter.setHandleWidth(0)
splitter.addWidget(v_left)
splitter.addWidget(v_middle)
splitter.addWidget(v_right)
layout.addWidget(splitter)
self.setLayout(layout)
self.setGeometry(100, 100, 1000, 800)
self.setWindowTitle('PiePy')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
I found the solution to my issue while I was working on setting up transparency. I added the line self.setAttribute(Qt.WA_NoSystemBackground, True) to my code and that made it clear in the application that there is indeed a space between the Qlabel and the splitter below it.
The solution was a simple one I just added layout.setSpacing(0) to the code and that took care of it.
You are using a QVBoxLayout where it will obey its default behavior, try putting your topbar inside a QHBoxLayout and adding this layout to your main layout(QVBoxLayout). Once you have this configuration add a stretch in each side of your topbar inside the QHBoxLayout to make it goes to the middle.
You would have something like that, from your code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os, sys
from PyQt5.QtWidgets import (QApplication, QWidget, QFrame, QSplitter, QStyleFactory,
QHBoxLayout, QVBoxLayout, QLabel)
from PyQt5.QtCore import Qt
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
#self.showFullScreen()
layout = QVBoxLayout()
layout_title = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
topbar = QLabel("example.py", self)
topbar.setAlignment(Qt.AlignVCenter)
topbar.setIndent(20)
topbar.setFixedHeight(35)
layout_title.addStretch(-1)
layout_title.addWidget(topbar)
layout_title.addStretch(-1)
layout.addLayout(layout_title)
v_left = QFrame(self)
v_left.setFrameShape(QFrame.StyledPanel)
v_middle = QFrame(self)
v_middle.setFrameShape(QFrame.StyledPanel)
v_right = QFrame(self)
v_right.setFrameShape(QFrame.StyledPanel)
splitter = QSplitter(Qt.Horizontal)
splitter.setHandleWidth(0)
splitter.addWidget(v_left)
splitter.addWidget(v_middle)
splitter.addWidget(v_right)
layout.addWidget(splitter)
self.setLayout(layout)
self.setGeometry(100, 100, 1000, 800)
self.setWindowTitle('PiePy')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
The logic is that you have something like that:
# [---------------------------------] <-main_layout (QVBoxLayout)
# item1 [---stretch----topbar----stretch] <-layout_title (QHBoxLayout)
# item2 [------------QSplitter----------]
# [---------------------------------] <-main_layout (QVBoxLayout)
Related
Why the sizePolicy doesn't affect on widgets that aren't in layout?
here is an example:
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([])
window = QtWidgets.QWidget()
window.setGeometry(50, 50, 500, 300)
test_widget = QtWidgets.QWidget(window)
test_widget.setMinimumSize(100, 100)
test_widget.setStyleSheet("background-color:red")
size_policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
test_widget.setSizePolicy(size_policy)
window.show()
app.exec()
But that doesn't work, if you changed the main window size the red box still has the same size.
So how can I make that red box resizeable when the parent (main window) is changing.
NOTE: I don't want to use Layouts for some reason.
I'm not sure I completely understand your GUI design but you should note that a single cell (as defined by a row/column pair) in a QGridLayout can be occupied by more than a single widget. A (very) simple example demonstrates this...
#!/usr/local/bin/python3
import os
import sys
from PySide2.QtWidgets import QApplication, QGridLayout, QLabel, QPushButton, QWidget
from PySide2.QtCore import Qt
class widget(QWidget):
def __init__ (self, parent = None):
super(widget, self).__init__(parent)
gl = QGridLayout(self)
pb = QPushButton("Show/Hide Menu")
self.menu = QLabel("Menu goes here...")
self.menu.setAlignment(Qt.AlignCenter)
self.menu.setStyleSheet("background-color: #40800000;")
canvas = QLabel("Canvas")
canvas.setAlignment(Qt.AlignCenter)
canvas.setStyleSheet("background-color: #40000080;")
gl.addWidget(pb, 0, 0)
gl.addWidget(canvas, 0, 0, 2, 2)
pb.raise_()
pb.clicked.connect(self.toggle_menu)
gl.addWidget(self.menu, 1, 0)
self.menu.hide()
def toggle_menu (self, checked):
self.menu.setVisible(not self.menu.isVisible())
if __name__ == '__main__':
app = QApplication([])
w = widget()
w.show()
app.exec_()
[I've used PySide2 as I don't have PyQt5 installed.]
So if I have understood correctly then I don't see why you can't make use of a QGridLayout. Could save you a lot of work.
I am following a bunch of guides I managed to come close to what I expect for my program to look. However with the solution I came to the button is added at the top-left corner of the main layout (layout_main), while I'd like it to be centered. This is my code:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
QApplication,
QLabel,
QMainWindow,
QPushButton,
QSizePolicy,
QTabWidget,
QVBoxLayout,
QWidget,
qApp,
)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Test")
self.setGeometry(0, 0, 1000, 700)
btn_start = QPushButton("Test button", self)
btn_start.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
btn_start.setMaximumSize(900, 500)
btn_start.setMinimumSize(200, 200)
lbl_test = QLabel("Test label", self)
layout_main = QVBoxLayout()
layout_main.addWidget(btn_start)
#layout_main.setAlignment(btn_start, Qt.AlignCenter)
layout_main.addWidget(lbl_test)
tabs = QTabWidget(self)
tabs.setTabPosition(QTabWidget.North)
tabs.setMovable(True)
main = QWidget(self)
main.setLayout(layout_main)
tabs.addTab(main, "Main tab")
self.setCentralWidget(tabs)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
And this is how it looks
When I tried to center it with layout_main.setAlignment(btn_start, Qt.AlignCenter), the commented line, then the button is centered, but sized down to the minimum size
How can I center the button while having it expand the way I want? I have tried lots of things like adding the button to it's own layout or inside a container widget, but no solution worked yet.
I run your code and find out that the btn_start.setMaximumSize limit the button to expand.
Edit your code as I told you now, if there are other problems comment and I will edit the solution.
Task:
For example (the code below) we create QHBoxLayout in which there are two buttons.
import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, QHBoxLayout, QApplication)
class Example(QWidget):
def __init__(self):
super().__init__()
hbox = QHBoxLayout()
okButton = QPushButton("OK")
cancelButton = QPushButton("Cancel")
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)
self.setLayout(hbox)
self.setGeometry(100, 100, 500, 500)
self.show()
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Necessary:
Set the size for hbox (QHBoxLayout) (W_pix, H_pix) and its coordinates (X_pos, Y_pos) on the main window (they do not fit, I did not find such functions in the documentation for the description for QHBoxLayout, QWidget).
v.2
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QRect
from PyQt5.QtWidgets import (QWidget, QPushButton,
QHBoxLayout, QApplication, QMainWindow, QVBoxLayout)
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.hbox = QVBoxLayout()
self.okButton = QPushButton("OK")
self.cancelButton = QPushButton("Cancel")
self.hbox.addWidget(self.okButton)
self.hbox.addWidget(self.cancelButton)
self.setGeometry(100, 100, 500, 500)
self.setLayout(self.hbox)
self.hbox.setGeometry(QtCore.QRect(200, 200, 300, 300))
self.show()
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
A QXLayout is not a visual element, so establishing the geometry (position and size) cannot be applied directly but must be interpreted.
The task of QHBoxLayout is to distribute widgets horizontally using as information the sizeHint, sizePolicy, minimum and maximum sizes, etc. and will use the maximum available size that gives the widget where it was established.
Considering the last point you can extrapolate your requirement to that widget since as described the geometry that handles the layout is that of that widget. So in this case a QWidget used as a container is created.
from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMainWindow, QPushButton, QWidget
class Example(QMainWindow):
def __init__(self):
super().__init__()
x_pos, y_pos = 10, 10
w_pix, h_pix = 150, 150
container = QWidget(self)
container.setContentsMargins(0, 0, 0, 0)
container.setFixedSize(w_pix, h_pix)
container.move(x_pos, y_pos)
container.setStyleSheet("background-color:salmon;")
hbox = QHBoxLayout(container)
hbox.setContentsMargins(0, 0, 0, 0)
self.okButton = QPushButton("OK")
self.cancelButton = QPushButton("Cancel")
hbox.addWidget(self.okButton)
hbox.addWidget(self.cancelButton)
self.resize(640, 480)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
I want my window to have this layout:
The graph will be from matplotlib.
I want a way of dynamically creating this layout, so that it would fit to any sized screen without changing the basic layout. How do I do this? This is what I've got so far:
import sys
from PyQt5.QtWidgets import (QWidget, QPushButton,
QHBoxLayout, QVBoxLayout, QApplication, QFrame, QScrollArea, QListWidget, QListWidgetItem, QLabel)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
#top left downwards
vbox = QVBoxLayout()
vbox.addStretch(1)
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addLayout(vbox)
hbox.setDirection(1)
self.setLayout(hbox)
qlist = QListWidget()
hbox.addWidget(qlist)
for i in range(0,31):
qlist.addItem(str(i))
qlist.setFrameStyle(QFrame.Raised)
vbox2 = QVBoxLayout()
vbox2.addStretch()
graph = QFrame(self)
graph.setStyleSheet("QWidget { background-color: red }" )
vbox2.addWidget(graph)
graph.setFrameShape(1)
self.setStyleSheet("font: 20pt Cambria")
self.showMaximized()
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Which gives me this:
Anyone know how to do this? I'm new to PyQt5 and am not sure how box layouts work after looking at multiple examples. Is there an easier way of doing this without the layout being disturbed?
Thanks!
The first thing you have to do is design your project, for example in your case you have two elements placed vertically: the red QFrame and something underneath, that something underneath commands an element handling the horizontal position so that below it must be a QHBoxLayout, and the element which places the QFrame and is something below it must be a QVBoxLayout, that is your simple structure that you could express it using the following scheme
QWidget
└── QVBoxLayout
├── QFrame
└── QHBoxLayout
└── QListWidget (with stretch = 1)
I prefer to create the widgets first and finally add it to the respective layouts.
import sys
from PyQt5 import QtWidgets
class Example(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# create widgets
graph = QtWidgets.QFrame()
graph.setFixedHeight(40)
graph.setFrameShape(QtWidgets.QFrame.Box)
graph.setStyleSheet("QWidget { background-color: red }" )
qlist = QtWidgets.QListWidget()
qlist.setFrameStyle(QtWidgets.QFrame.Raised)
qlist.addItems(map(str, range(31)))
# create QHBoxLayout and add QListWidget
hlay = QtWidgets.QHBoxLayout()
hlay.addWidget(qlist)
hlay.addStretch(1)
# create QVBoxLayout and add QFrame and QHBoxLayout
vlay = QtWidgets.QVBoxLayout(self)
vlay.addWidget(graph)
vlay.addLayout(hlay)
self.setStyleSheet("font: 20pt Cambria")
self.showMaximized()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Note: The QFrame does not have a certain height because its task is to take the task of the content, in this case there is not so we must establish a fixed size, if you are going to add elements to the QFrame do it through a layout and eliminate the line of setFixedHeight().
I am new to GUI development and I am trying to learn how to use pyqt5 in python.
Below is the example code I am working on. I want a window with some checkboxes,combobox and radiobuttons on the right side of the window. The details of the QtWidget objects are in the code.
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy, QWidget, QPushButton, QComboBox, QRadioButton, QVBoxLayout, QCheckBox
from PyQt5.QtGui import QIcon
class App(QMainWindow):
def __init__(self):
super().__init__()
self.left = 0
self.top = 500
self.title = 'Chip2 Torque Data'
self.width = 500
self.height =500
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
xselect=QRadioButton("X",self)
xselect.setChecked(True)
xselect.move(340,400)
zselect=QRadioButton("Z",self)
zselect.move(380,400)
sselect=QRadioButton("SP1",self)
sselect.move(420,400)
pass_list=QComboBox(self)
pass_list.addItems(sheets_idealcut)
pass_list.move(340,300)
rawdata_check=QCheckBox("Raw Data",self)
rawdata_check.setChecked(True)
rawdata_check.move(340,200)
mvgavg_check=QCheckBox("Moving average",self)
mvgavg_check.setChecked(True)
mvgavg_check.move(380,200)
mvgstd_check=QCheckBox("Moving stdev",self)
mvgstd_check.setChecked(True)
mvgstd_check.move(420,200)
self.show()
if __name__ == '__main__':
sheets_idealcut=['pass2','pass3','pass4','pass5']
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
else:
print('QApplication instance already exists: %s' % str(app))
ex = App()
#ex.show()
app.exec_()
Below is the output of the code. (Please ignore the overlapping checkbox names. I intend to correct it later.)
My problem is when I maximise this window, the QtWidget objects(QComboBox,QRadioButton,QCheckBox) don't readjust their position with the new window size.
So for the widgets to reposition themselves automatically, what method should be used ?
I googled it but I couldn't find anything useful.
Please help.
You are using move(x,y) which sets the Widgets to a specific fixed position. So you could write a function which is called on maximizing the window and then reposition your widgets accordingly.
Another automated approach is to use box layouts. QtGui.QHBoxLayout and QtGui.QVBoxLayout are basic layout classes which lines up widgets horizontally or vertically. From your pictures I do not know what exact positions you want your widgets to end up, so I try to explain it like I think you want it.
Each row of elements can be assigned into a HBox like this:
hbox = QtGui.QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(rawdata_check)
hbox.addWidget(mvgavg_check)
hbox.addWidget(mvgstd_check)
If you then resize the window the widgets should automaticly be repositioned to the right side of the window. The QtDesigner can help you arranging all the elements.
You should be using layouts for dynamic sizing. There are alot of different layouts. The layouts used in this example is the most basic types. I also changed the parent of "App" to a QDialog. They are easier to handle.
Here is an example of your app, using layouts:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy, QWidget, QPushButton, QComboBox, QRadioButton, \
QVBoxLayout, QCheckBox, QHBoxLayout, QGroupBox, QDialog
from PyQt5.QtGui import QIcon
class App(QDialog):
def __init__(self):
super().__init__()
self.left = 0
self.top = 500
self.title = 'Chip2 Torque Data'
self.width = 500
self.height = 500
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.main_layout = QVBoxLayout()
xselect=QRadioButton("X",self)
xselect.setChecked(True)
# xselect.move(340,400)
self.main_layout.addWidget(xselect)
zselect=QRadioButton("Z",self)
# zselect.move(380,400)
self.main_layout.addWidget(zselect)
sselect=QRadioButton("SP1",self)
# sselect.move(420,400)
self.main_layout.addWidget(sselect)
pass_list=QComboBox(self)
pass_list.addItems(sheets_idealcut)
self.main_layout.addWidget(pass_list)
#pass_list.move(340,300)
rawdata_check=QCheckBox("Raw Data",self)
rawdata_check.setChecked(True)
self.main_layout.addWidget(rawdata_check)
#rawdata_check.move(340,200)
mvgavg_check=QCheckBox("Moving average",self)
mvgavg_check.setChecked(True)
#mvgavg_check.move(380,200)
mvgstd_check=QCheckBox("Moving stdev",self)
mvgstd_check.setChecked(True)
#mvgstd_check.move(420,200)
self.check_group = QHBoxLayout()
self.check_group.addWidget(mvgavg_check)
self.check_group.addWidget(mvgstd_check)
self.check_group.stretch(1)
self.main_layout.addLayout(self.check_group)
self.setLayout(self.main_layout)
self.show()
if __name__ == '__main__':
sheets_idealcut=['pass2','pass3','pass4','pass5']
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
else:
print('QApplication instance already exists: %s' % str(app))
ex = App()
#ex.show()
app.exec_()