I am trying to create a PyQt5 - QLabel with both image and text. I would like to have a text at the bottom of the image. Below is a part of the code
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Window(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
l4=QLabel()
l4.setText('delete')
l4.setAlignment(Qt.AlignBottom)
pixmap = QPixmap("/home/moh/Documents/My_GUI/Icons/Delete.png")
l4.setPixmap(pixmap)
l4.setAlignment(Qt.AlignTop)
self.layout = QGridLayout()
self.layout.addWidget(l4, 0, 0)
self.setLayout(self.layout)
self.show()
app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())
You have to use 2 QLabel in a QVBoxLayout:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
pixmap_label = QLabel(
pixmap=QPixmap("/home/moh/Documents/My_GUI/Icons/Delete.png")
)
text_label = QLabel(text="delete")
lay = QVBoxLayout(self)
lay.addWidget(pixmap_label, alignment=Qt.AlignCenter)
lay.addWidget(text_label, alignment=Qt.AlignCenter)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
If you want to use a circle Qlabel image, use this code:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QPainterPath, QPainter
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
class Label(QLabel):
def __init__(self, *args, antialiasing=True, **kwargs):
super(Label, self).__init__(*args, **kwargs)
self.Antialiasing = antialiasing
self.setMaximumSize(90, 90)
self.setMinimumSize(90, 90)
self.radius = 45
self.target = QPixmap(self.size())
self.target.fill(Qt.transparent)
p = QPixmap("Image.jpg").scaled(
90, 90, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)
painter = QPainter(self.target)
if self.Antialiasing:
painter.setRenderHint(QPainter.Antialiasing, True)
painter.setRenderHint(QPainter.HighQualityAntialiasing, True)
painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
path = QPainterPath()
path.addRoundedRect(
0, 0, self.width(), self.height(), self.radius, self.radius)
painter.setClipPath(path)
painter.drawPixmap(0, 0, p)
self.setPixmap(self.target)
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
pixmap_label = Label()
text_label = QLabel(text="delete")
lay = QVBoxLayout(self)
lay.addWidget(pixmap_label, alignment=Qt.AlignCenter)
lay.addWidget(text_label, alignment=Qt.AlignCenter)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
Related
I am trying to display an image from a URL in pyside6, but can't get anything to work.
def getIcon(data):
iconID = data['weather'][0]['icon']
icon = QPixmap("http://openweathermap.org/img/w/" + iconID + ".png");
return icon
And
self.temperatureIcon = QtWidgets.QLabel(self).setPixmap(getIcon(self.weatherData))
is the code I have.
QPixmap does not download the image from a url so you must download it for example using QNetworkAccessManager:
import sys
from functools import cached_property
from PySide6.QtCore import Signal, QObject, Qt, QUrl
from PySide6.QtGui import QImage, QPixmap
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
from PySide6.QtWidgets import (
QApplication,
QGridLayout,
QLabel,
QLineEdit,
QPushButton,
QWidget,
)
class ImageDownloader(QObject):
finished = Signal(QImage)
def __init__(self, parent=None):
super().__init__(parent)
self.manager.finished.connect(self.handle_finished)
#cached_property
def manager(self):
return QNetworkAccessManager()
def start_download(self, url):
self.manager.get(QNetworkRequest(url))
def handle_finished(self, reply):
if reply.error() != QNetworkReply.NoError:
print("error: ", reply.errorString())
return
image = QImage()
image.loadFromData(reply.readAll())
self.finished.emit(image)
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.lineedit = QLineEdit()
self.button = QPushButton("Start")
self.label = QLabel(alignment=Qt.AlignCenter)
lay = QGridLayout(self)
lay.addWidget(self.lineedit, 0, 0)
lay.addWidget(self.button, 0, 1)
lay.addWidget(self.label, 1, 0, 1, 2)
self.downloader = ImageDownloader()
self.downloader.finished.connect(self.handle_finished)
self.button.clicked.connect(self.handle_clicked)
self.lineedit.setText("http://openweathermap.org/img/wn/01d#2x.png")
self.resize(640, 480)
def handle_finished(self, image):
pixmap = QPixmap.fromImage(image)
self.label.setPixmap(pixmap)
def handle_clicked(self):
url = QUrl.fromUserInput(self.lineedit.text())
self.downloader.start_download(url)
def main():
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()
Here's another simple solution\example:
import sys
import requests
from PySide6.QtGui import QPixmap, QScreen
from PySide6.QtWidgets import QApplication, QWidget, QLabel
URL = 'https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_(test_image).png'
class App(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('getAndSetImageFromURL()')
self.label = QLabel(self)
self.pixmap = QPixmap()
self.getAndSetImageFromURL(URL)
self.resize(self.pixmap.width(),self.pixmap.height())
screenSize = QScreen.availableGeometry(QApplication.primaryScreen())
frmX = (screenSize.width () - self.width ())/2
frmY = (screenSize.height() - self.height())/2
self.move(frmX, frmY)
self.show()
def getAndSetImageFromURL(self,imageURL):
request = requests.get(imageURL)
self.pixmap.loadFromData(request.content)
self.label.setPixmap(self.pixmap)
#QApplication.processEvents() # uncoment if executed on loop
if __name__ == '__main__':
app = QApplication(sys.argv)
gui = App()
sys.exit(app.exec())
which outputs:
import sys
import requests
import PySide6
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
from PySide6.QtWidgets import QTableView, QWidget, QApplication, QGridLayout, QHeaderView
from PySide6.QtCore import Qt, QAbstractTableModel, QObject, Signal, QUrl
from PySide6.QtGui import QColor, QIcon, QPixmap, QImage
from datetime import datetime
class MagicIcon():
def __init__(self, link):
self.link = link
self.icon = QIcon()
try:
response = requests.get(self.link)
pixmap = QPixmap()
pixmap.loadFromData(response.content)
self.icon = QIcon(pixmap)
except:
pass
class MainWindow(QWidget):
def __init__():
super().__init__()
self.setWindowIcon(MagicIcon(
"https://img.icons8.com/external-flatarticons-blue-flatarticons/65/000000/external-analysis-digital-marketing-flatarticons-blue-flatarticons-1.png"
).icon)
if __name__ == "__main__":
app = QApplication(sys.argv)
wid = MainWindow()
wid.show()
sys.exit(app.exec())
Use requests module to fetch image and store them.
How can I have multiple QGridLayouts on a single widget? I want to have one grid layout on the left and one on the right.
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class FormWidget(QWidget):
def __init__(self):
super(FormWidget, self).__init__( )
self.grid = QGridLayout(self)
self.grid2 = QGridLayout(self)
self.grid.addWidget(self.grid2)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = FormWidget()
sys.exit(app.exec_())
If you want to place 2 layouts horizontally then you must use a QHBoxLayout:
import sys
from PyQt5.QtWidgets import QApplication, QGridLayout, QHBoxLayout, QWidget
class FormWidget(QWidget):
def __init__(self, parent=None):
super(FormWidget, self).__init__(parent)
left_grid_layout = QGridLayout()
right_grid_layout = QGridLayout()
lay = QHBoxLayout(self)
lay.addLayout(left_grid_layout)
lay.addLayout(right_grid_layout)
self.resize(640, 480)
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = FormWidget()
ex.show()
sys.exit(app.exec_())
Update:
If you want to set a weight you must set it in the stretch.
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QGridLayout, QHBoxLayout, QTextEdit, QWidget
class FormWidget(QWidget):
def __init__(self, parent=None):
super(FormWidget, self).__init__(parent)
left_grid_layout = QGridLayout()
right_grid_layout = QGridLayout()
# for testing
left_grid_layout.addWidget(QTextEdit())
right_grid_layout.addWidget(QTextEdit())
lay = QHBoxLayout(self)
lay.addLayout(left_grid_layout, stretch=1)
lay.addLayout(right_grid_layout, stretch=2)
lay.setContentsMargins(
0, # left
100, # top
0, # right
100 # bottom
)
self.resize(640, 480)
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = FormWidget()
ex.show()
sys.exit(app.exec_())
I want my window and it's QGraphicsScene to be transparent which is controlled by QSlider.
I tried looking for some answers here and there, but it's mainly setting background color to 0 :
self.setStyleSheet("background-color:rgba(0, 0, 0, 0);")
or like that :
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
Which does it job, but I would like to make slider which will control level of transparency and I don't see how can I do it with commands above.
Can somebody please give me some advise how to do it ? Thank you
I will attach my test code here below(I want to be able to control transparency of everything , but do not touch slider and button):
from PySide2.QtGui import QBrush, QColor
from PySide2.QtCore import QSize, Qt
from PySide2.QtWidgets import QDialog, QVBoxLayout, QGraphicsView, QGraphicsScene, QFrame, QSizePolicy, QApplication, QSlider, QPushButton
class MainWindow(QDialog):
def __init__(self):
QDialog.__init__(self)
self.mainLayout = QVBoxLayout()
self.graphicsWidget = MainGraphicsWidget()
self.window = 'transp_test'
self.title = 'transparent UI'
self.size = (1000, 650)
self.create()
def create(self, **kwargs):
self.setWindowTitle(self.title)
self.resize(QSize(*self.size))
self.setLayout(self.mainLayout)
self.mainLayout.addWidget(self.graphicsWidget)
class MainGraphicsWidget(QGraphicsView):
def __init__(self, parent=None):
super(MainGraphicsWidget, self).__init__(parent)
self._scene = QGraphicsScene(backgroundBrush = Qt.gray)
self.setScene(self._scene)
self.transpSlider = QSlider()
self.transpSlider.setRange(0,100)
self.mainButton = QPushButton('I want it to be "Test" button')
self._scene.addWidget(self.mainButton)
self._scene.addWidget(self.transpSlider)
self.transpSlider.move(300, 100)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setBackgroundBrush(QBrush(QColor(30, 30, 30)))
self.setFrameShape(QFrame.NoFrame)
self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.setGeometry(600, 300, 600, 600)
window.show()
sys.exit(app.exec_())
Here is one way.
class MainWindow(QDialog):
def __init__(self):
QDialog.__init__(self)
# these two lines are needed to get a transparent background in windows
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
# rest of class definition unchanged
class MainGraphicsWidget(QGraphicsView):
def __init__(self, parent=None):
super(MainGraphicsWidget, self).__init__(parent)
# set transparent background color for the widget itself
self.setStyleSheet("background-color: #00000000")
self._scene = QGraphicsScene()
self.setScene(self._scene)
# create of slider and connect to slot for changing opacity.
self.transpSlider = QSlider()
self.transpSlider.setStyleSheet('background-color: #00000000')
self.transpSlider.setRange(0,255)
self.transpSlider.valueChanged.connect(self.set_opacity)
self.transpSlider.setValue(255)
# rest of __init__ unchanged
def set_opacity(self, value):
brush = self.backgroundBrush()
color = brush.color()
color.setAlpha(value)
brush.setColor(color)
self.setBackgroundBrush(color)
Note that I've changed the range of the slider to 0-255 to make changing the opacity from fully opaque to fully transparent easier.
Try it:
#from PySide2.QtGui import QBrush, QColor
#from PySide2.QtCore import QSize, Qt
#from PySide2.QtWidgets import QDialog, QVBoxLayout, QGraphicsView, QGraphicsScene, QFrame, QSizePolicy, QApplication, QSlider, QPushButton
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtGui import QBrush, QColor
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QGraphicsView, QGraphicsScene,
QFrame, QSizePolicy, QApplication, QSlider, QPushButton)
class MainGraphicsWidget(QGraphicsView):
def __init__(self, parent=None):
super(MainGraphicsWidget, self).__init__(parent)
self._scene = QGraphicsScene()
self.setScene(self._scene)
self.transpSlider = QtWidgets.QSlider(
QtCore.Qt.Horizontal,
minimum=10,
maximum=100,
value=100,
valueChanged=self.onValueChanged,
)
self.mainButton = QPushButton('I want it to be "Test" button \n QUIT')
self.mainButton.resize(150, 150)
self.mainButton.clicked.connect(parent.close)
self._scene.addWidget(self.mainButton)
self._scene.addWidget(self.transpSlider)
self.transpSlider.move(300, 100)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
c = QColor(220, 30, 30)
c.setAlphaF(1)
self.setBackgroundBrush(QBrush(c))
self.setFrameShape(QFrame.NoFrame)
self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
#QtCore.pyqtSlot(int)
def onValueChanged(self, value):
c = QColor(220, 30, 30)
c.setAlphaF(value * 0.01)
self.setBackgroundBrush(QBrush(c))
window.setWindowOpacity(value * 0.03)
self.setStyleSheet("MainGraphicsWidget {{background-color: rgba(0, 215, 55, {});}}".format(value))
class MainWindow(QDialog):
def __init__(self):
super().__init__()
self.setAttribute(Qt.WA_NoSystemBackground, False)
self.setStyleSheet("MainWindow {background-color: rgba(0, 215, 55, 70);}")
self.graphicsWidget = MainGraphicsWidget(self)
self.window = 'transp_test'
self.title = 'transparent UI'
self.size = (1000, 650)
self.setWindowTitle(self.title)
self.resize(QSize(*self.size))
self.mainLayout = QVBoxLayout()
self.setLayout(self.mainLayout)
self.mainLayout.addWidget(self.graphicsWidget)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.setGeometry(600, 100, 600, 600)
window.show()
sys.exit(app.exec_())
I have a QMainWindow with a toolbar, and I'm having troubles with fitting the QPixmap to the window, such that it won't tackle with the toolbar.
I want to display the picture:
And from the code:
import sys
from PyQt5.QtCore import QRect
from PyQt5.QtWidgets import QAction, QMainWindow, QApplication
from PyQt5.QtGui import QPixmap, QPainter
class Menu(QMainWindow):
def __init__(self):
super().__init__()
newAct = QAction('New', self)
self.toolbar = self.addToolBar('Remove')
self.toolbar.addAction(newAct)
self.image = QPixmap("background.png")
self.setGeometry(100, 30, 500, 300)
self.resize(self.image.width(), self.image.height())
self.show()
def paintEvent(self, event):
painter = QPainter(self)
rect = QRect(0, 0, self.image.width(), self.image.height())
painter.drawPixmap(rect, self.image)
if __name__ == '__main__':
app = QApplication(sys.argv)
mainMenu = Menu()
sys.exit(app.exec_())
I get:
And as you can see, The picture is on the toolbar as well, and I don't want that.
Another try:
import sys
from PyQt5.QtCore import QRect
from PyQt5.QtWidgets import QAction, QMainWindow, QApplication
from PyQt5.QtGui import QPixmap, QPainter
class Menu(QMainWindow):
def __init__(self):
super().__init__()
newAct = QAction('New', self)
self.toolbar = self.addToolBar('Remove')
self.toolbar.addAction(newAct)
self.image = QPixmap("background.png")
self.setGeometry(100, 30, 500, 300)
self.resize(self.image.width(), self.image.height() + self.toolbar.height())
self.show()
def paintEvent(self, event):
painter = QPainter(self)
rect = QRect(0, self.toolbar.height(), self.image.width(), self.image.height() + self.toolbar.height())
painter.drawPixmap(rect, self.image)
if __name__ == '__main__':
app = QApplication(sys.argv)
mainMenu = Menu()
sys.exit(app.exec_())
But I get:
And as you can see, I don't see one of the lines (the blue one).
How can I fix it, so the picture will fit the window excluding the toolbar?
In addition to that, it means I'll have to change all my mouse clicks to move the y-axis. Is there perhaps a way I can set everything such that (x,y)=(0,0) would be at the uppermost left, below the toolbar?
I'm using Python 3.6.5 |Anaconda custom (64-bit) on windows | PyQt version: 5.9.2
Although I can not reproduce the problem, the following solution must work, in it I draw the image in a widget and I set them as centralwidget.
import sys
from PyQt5.QtCore import QRect
from PyQt5.QtWidgets import QAction, QMainWindow, QApplication, QWidget
from PyQt5.QtGui import QPixmap, QPainter
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.image = QPixmap("background.png")
self.setFixedSize(self.image.size())
def paintEvent(self, event):
painter = QPainter(self)
painter.drawPixmap(self.rect(), self.image)
class Menu(QMainWindow):
def __init__(self):
super().__init__()
newAct = QAction('New', self)
self.toolbar = self.addToolBar('Remove')
self.toolbar.addAction(newAct)
self.setCentralWidget(Widget())
self.setFixedSize(self.sizeHint())
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainMenu = Menu()
sys.exit(app.exec_())
I'm having a hard time understanding how to use scroll bars in PyQt5. I have an arbitrary layout to experiment with, which is just some blocks of colors. I'd like to have the layout of colors to have a minimum size, and when the window is smaller than that, the scroll bars appear (or the scroll bars are just present all the time). I found this example:
PyQt: Put scrollbars in this
and changed it to work with PyQt5:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QScrollArea, QVBoxLayout, QWidget
class myDialog(QDialog):
_buttons = 0
def __init__(self, parent=None):
super(myDialog, self).__init__(parent)
self.pushButton = QPushButton(self)
self.pushButton.setText("Add Button!")
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.scrollArea = QScrollArea(self)
self.scrollArea.setWidgetResizable(True)
self.scrollAreaWidgetContents = QWidget(self.scrollArea)
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 380, 247))
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout = QVBoxLayout(self)
self.verticalLayout.addWidget(self.pushButton)
self.verticalLayout.addWidget(self.scrollArea)
self.verticalLayoutScroll = QVBoxLayout(self.scrollAreaWidgetContents)
'''
verticalLayoutScroll is a child of scrollAreaWidgetContents
scrollAreaWidgetContents is a child of scrollArea
scrollArea is child of self
verticalLayout is also a child of self has the widgets pushButton and scrollArea
'''
#QtCore.pyqtSlot()
def on_pushButton_clicked(self):
self._buttons += 1
pustButtonName = u"Button {0}".format(self._buttons)
pushButton = QPushButton(self.scrollAreaWidgetContents)
pushButton.setText(pustButtonName)
self.verticalLayoutScroll.addWidget(pushButton)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
app.setApplicationName('myDialog')
main = myDialog()
main.show()
sys.exit(app.exec_())
Here is my code:
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 07:37:28 2018
#author: Erik
"""
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QSlider, QPushButton,
QMainWindow, QAction, qApp,
QLCDNumber, QGridLayout, QLabel, QLineEdit, QVBoxLayout, QHBoxLayout,
QSizePolicy, QScrollArea, QLayout)
from PyQt5.QtGui import QIcon, QColor, QPalette
from PyQt5.QtCore import Qt, QSize, QRect
class Color(QWidget):
def __init__(self, color, *args, **kwargs):
super(Color, self).__init__(*args, **kwargs)
self.setAutoFillBackground(True)
palette = self.palette()
palette.setColor(QPalette.Window, QColor(color))
self.setPalette(palette)
class Color2(QWidget):
def __init__(self, color, *args, **kwargs):
super(Color2, self).__init__(*args, **kwargs)
self.setAutoFillBackground(True)
palette = self.palette()
palette.setColor(QPalette.Window, QColor(color))
self.setPalette(palette)
def sizeHint(self):
return QSize(150,150)
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("My Awesome App")
size = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
layout = QVBoxLayout()
layout2 = QVBoxLayout()
brw = Color2('brown')
brw.setSizePolicy(size)
layout2.addWidget(brw)
layout2.addWidget(Color('black'))
layout2.setStretch(1,2)
layout2.addWidget(Color('cyan'))
layout2.setStretch(2, 1)
layout.addWidget(Color('red'))
layout.addWidget(Color('blue'))
layout.addWidget(Color('green'))
self.scrollArea = QScrollArea(self)
self.scrollArea.setWidgetResizable(True)
self.scrollAreaWidgetContents = QWidget(self.scrollArea)
self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 600, 500))
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scrollAreaWidgetContents.setMinimumSize(QSize(500, 500))
self.scrollLayout = QVBoxLayout(self.scrollAreaWidgetContents)
#self.scrollLayout.setSizeConstraint(QLayout.SetMinimumSize) #2
self.mainLayout = QHBoxLayout()
self.mainLayout.addWidget(Color('purple'))
self.mainLayout.addWidget(Color('yellow'))
self.mainLayout.addWidget(Color('orange'))
self.mainLayout.addLayout(layout2)
self.mainLayout.addLayout(layout)
self.scrollLayout.addLayout(self.mainLayout)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainWindow()
sys.exit(app.exec_())
I can barely see the colors in the scrollArea. In the first code block above, I don't understand the necessary inheritance structure I described in the comment block. Do I need to extend a layout class to set a minimum size?
https://doc.qt.io/qt-5/qlayoutitem.html#minimumSize
How is the "Size Hints and Layouts" section of https://doc.qt.io/qt-5/qscrollarea.html#details relevant?
Thanks.
The problem is that you have not established the QScrollArea as centralWidget.
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("My Awesome App")
size = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
layout = QVBoxLayout()
layout2 = QVBoxLayout()
brw = Color2('brown')
brw.setSizePolicy(size)
layout2.addWidget(brw)
layout2.addWidget(Color('black'))
layout2.setStretch(1,2)
layout2.addWidget(Color('cyan'))
layout2.setStretch(2, 1)
layout.addWidget(Color('red'))
layout.addWidget(Color('blue'))
layout.addWidget(Color('green'))
self.scrollArea = QScrollArea()
# set CentralWidget
self.setCentralWidget(self.scrollArea)
self.scrollArea.setWidgetResizable(True)
self.scrollAreaWidgetContents = QWidget(self.scrollArea)
self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 600, 500))
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scrollAreaWidgetContents.setMinimumSize(QSize(500, 500))
self.scrollLayout = QVBoxLayout(self.scrollAreaWidgetContents)
#self.scrollLayout.setSizeConstraint(QLayout.SetMinimumSize) #2
self.mainLayout = QHBoxLayout()
self.mainLayout.addWidget(Color('purple'))
self.mainLayout.addWidget(Color('yellow'))
self.mainLayout.addWidget(Color('orange'))
self.mainLayout.addLayout(layout2)
self.mainLayout.addLayout(layout)
self.scrollLayout.addLayout(self.mainLayout)
self.show()