How do I go about creating a dynamic grid QScrollarea in PyQt5? - python

I'm developing some custom software that involves creating a workspace and working in it. I want to display all the existing workSpace directories in a dynamic scrollarea grid comprised of buttons that changes the positions of the buttons depending on the amount of screen real estate the scrollarea is taking up so that as many buttons as possible are inserted in the highest possible row.( So basically like the file explorer changes the layout of the folders and files to fit the screen in a grid depending on how you resize the window) I tried doing this using a gridlayout inside the scrollarea. I also tried to add qhboxlayouts in a qvboxlayout to no avail since I had no idea how to check whether there is space for another button to remove one from a lower qhboxlayout and append to a higher one.
This is my current code:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog
class Ui_AutoCal(object):
def setupUi(self, AutoCal):
AutoCal.setObjectName("AutoCal")
AutoCal.resize(513, 551)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(AutoCal.sizePolicy().hasHeightForWidth())
AutoCal.setSizePolicy(sizePolicy)
AutoCal.setCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))
AutoCal.setStyleSheet("*{\n"
"background-color: rgb(54, 54, 54);\n"
"color:rgb(255,255,255)\n"
"}\n"
"\n"
"QPushButton\n"
"{\n"
"border-radius: 25px;\n"
"}\n"
"\n"
"QLineEdit\n"
"{\n"
"color:rgb(0,0,0)\n"
"}")
self.centralwidget = QtWidgets.QWidget(AutoCal)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setAlignment(QtCore.Qt.AlignCenter)
self.groupBox.setObjectName("groupBox")
self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.groupBox)
self.verticalLayout_6.setObjectName("verticalLayout_6")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.label = QtWidgets.QLabel(self.groupBox)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setObjectName("label")
self.horizontalLayout_3.addWidget(self.label)
self.lineEdit = QtWidgets.QLineEdit(self.groupBox)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
self.lineEdit.setSizePolicy(sizePolicy)
self.lineEdit.setObjectName("lineEdit")
self.horizontalLayout_3.addWidget(self.lineEdit)
self.pushButton = QtWidgets.QPushButton(self.groupBox)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setObjectName("pushButton")
# self.pushButton.clicked.connect(self.openFileNameDialog )
self.horizontalLayout_3.addWidget(self.pushButton)
self.verticalLayout_6.addLayout(self.horizontalLayout_3)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.label_2 = QtWidgets.QLabel(self.groupBox)
self.label_2.setObjectName("label_2")
self.horizontalLayout_4.addWidget(self.label_2)
self.lineEdit_2 = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_2.setText("")
self.lineEdit_2.setObjectName("lineEdit_2")
self.horizontalLayout_4.addWidget(self.lineEdit_2)
self.pushButton_2 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout_4.addWidget(self.pushButton_2)
self.verticalLayout_6.addLayout(self.horizontalLayout_4)
self.verticalLayout.addWidget(self.groupBox)
self.verticalLayout_3 = QtWidgets.QVBoxLayout()
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_2.setEnabled(True)
self.groupBox_2.setAlignment(QtCore.Qt.AlignCenter)
self.groupBox_2.setObjectName("groupBox_2")
self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.groupBox_2)
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.scrollArea = QtWidgets.QScrollArea(self.groupBox_2)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollArea.sizePolicy().hasHeightForWidth())
self.scrollArea.setSizePolicy(sizePolicy)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.gridLayout = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)
# self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 467, 331))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.fillScrollArea()
self.verticalLayout_5.addWidget(self.scrollArea)
self.verticalLayout_3.addWidget(self.groupBox_2)
self.verticalLayout.addLayout(self.verticalLayout_3)
AutoCal.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(AutoCal)
self.menubar.setGeometry(QtCore.QRect(0, 0, 513, 22))
self.menubar.setObjectName("menubar")
self.menuWorkSpace = QtWidgets.QMenu(self.menubar)
self.menuWorkSpace.setObjectName("menuWorkSpace")
self.menuRecipients = QtWidgets.QMenu(self.menubar)
self.menuRecipients.setObjectName("menuRecipients")
AutoCal.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(AutoCal)
self.statusbar.setObjectName("statusbar")
AutoCal.setStatusBar(self.statusbar)
self.menubar.addAction(self.menuWorkSpace.menuAction())
self.menubar.addAction(self.menuRecipients.menuAction())
self.retranslateUi(AutoCal)
QtCore.QMetaObject.connectSlotsByName(AutoCal)
def retranslateUi(self, AutoCal):
_translate = QtCore.QCoreApplication.translate
AutoCal.setWindowTitle(_translate("AutoCal", "AutoCal"))
self.groupBox.setTitle(_translate("AutoCal", "Create New WorkSpace"))
self.label.setText(_translate("AutoCal", "Choose WorkSpace Directory"))
self.pushButton.setText(_translate("AutoCal", "Browse"))
self.label_2.setText(_translate("AutoCal", "WorkSpace Name"))
self.pushButton_2.setText(_translate("AutoCal", "Create"))
self.groupBox_2.setTitle(_translate("AutoCal", "Choose Existing WorkSpace"))
self.menuWorkSpace.setTitle(_translate("AutoCal", "WorkSpace"))
self.menuRecipients.setTitle(_translate("AutoCal", "Recipients"))
def fillScrollArea(self):
for i in range(50):
for j in range(50):
self.gridLayout.addWidget(QtWidgets.QPushButton("Test"), i, j)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
AutoCal = QtWidgets.QMainWindow()
ui = Ui_AutoCal()
ui.setupUi(AutoCal)
AutoCal.show()
sys.exit(app.exec_())
This produces the following scrollArea (ignore the forms):
Current Scroll Area
The main problem is that i need the buttons to always be in the visible section of the scrollArea, whereas as you can see many of them are hidden behind the scrollarea and their text is cut off. I know this is because of the positioning that my function applies to the grid layout but I'm not aware of any other way to position them. I also need the buttons to be dynamic in the sense that if horizontal space becomes greater in a higher row, the ones in the lower row will take up that space. Because of this I dont need horizontal scrolling either, which is why it's disabled.

My issue is now resolved. While flow layout was useful, it was much more intuitive to simply use QListWidget. Many thanks to both eyllanesc and musicamante for their help.
For anyone who has the same issue, the desired result can be achieved by simply creating a QlistWidget and adding items to it:
size = QSize(100,100)
self.listWidget = QListWidget()
size = QtCore.QSize(80,80)
self.listWidget.setResizeMode(QListView.Adjust)
self.listWidget.setIconSize(size)
self.listWidget.itemDoubleClicked.connect(self.itemClicked)
self.listWidget.setViewMode(QListView.IconMode)

Related

Getting the error "QGraphicsView(QGraphicsScene, parent: QWidget = None): argument 1 has unexpected type 'QWidget'"

Its my first time working with PyQt5 and I can't figure out why I'm getting this error. I've run my code line by line to try and understand where I am getting the error, and as per my understanding it's this part of my code that is creating the issue:
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.Single = QtWidgets.QPushButton(self.centralwidget)
self.Single.setGeometry(QtCore.QRect(270, 440, 130, 28))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Single.sizePolicy().hasHeightForWidth())
self.Single.setSizePolicy(sizePolicy)
self.Single.setMinimumSize(QtCore.QSize(130, 28))
self.Single.setMaximumSize(QtCore.QSize(120, 28))
font = QtGui.QFont()
font.setPointSize(10)
self.Single.setFont(font)
self.Single.setObjectName("Single")
self.Single.clicked.connect(self.Capture)
self.graphicsView = pg.PlotWidget(self.centralwidget)
In case that bit wasn't the problem, here is the entire relevant section of my code:
import sys
import pyqtgraph as pg
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QWidget, QInputDialog, QLineEdit, QFileDialog
from PyQt5.QtCore import QObject, pyqtSlot
from PyQt5.QtGui import QPen
class Ui_MainWindow(QWidget):
def setupUi(self, MainWindow): #holds the GUI
MainWindow.setObjectName("MainWindow")
MainWindow.resize(795, 522)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.Single = QtWidgets.QPushButton(self.centralwidget)
self.Single.setGeometry(QtCore.QRect(270, 440, 130, 28))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Single.sizePolicy().hasHeightForWidth())
self.Single.setSizePolicy(sizePolicy)
self.Single.setMinimumSize(QtCore.QSize(130, 28))
self.Single.setMaximumSize(QtCore.QSize(120, 28))
font = QtGui.QFont()
font.setPointSize(10)
self.Single.setFont(font)
self.Single.setObjectName("Single")
self.Single.clicked.connect(self.Capture)
self.graphicsView = pg.PlotWidget(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(10, 10, 771, 421))
self.graphicsView.setMinimumSize(QtCore.QSize(771, 421))
self.graphicsView.setXRange(440, 760, padding=0)
self.graphicsView.setYRange(-0.1, 2.1, padding=0)
self.graphicsView.setAutoFillBackground(True)
self.graphicsView.setFrameShape(QtWidgets.QFrame.Box)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.NoBrush)
self.graphicsView.setBackgroundBrush(QtCore.Qt.white)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.NoBrush)
self.graphicsView.setForegroundBrush(brush)
self.graphicsView.setObjectName("graphicsView")
self.graphicsView.showGrid(x=True, y=True, alpha=0.3)
self.graphicsView.showMaximized()
self.STOP = QtWidgets.QPushButton(self.centralwidget)
self.STOP.setGeometry(QtCore.QRect(720, 440, 60, 28))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.STOP.sizePolicy().hasHeightForWidth())
self.STOP.setSizePolicy(sizePolicy)
self.STOP.setMinimumSize(QtCore.QSize(60, 28))
self.STOP.setMaximumSize(QtCore.QSize(60, 28))
font = QtGui.QFont()
font.setPointSize(10)
self.STOP.setFont(font)
self.STOP.setObjectName("STOP")
self.Continuous = QtWidgets.QPushButton(self.centralwidget)
self.Continuous.setGeometry(QtCore.QRect(410, 440, 130, 28))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Continuous.sizePolicy().hasHeightForWidth())
self.Continuous.setSizePolicy(sizePolicy)
self.Continuous.setMinimumSize(QtCore.QSize(130, 28))
self.Continuous.setMaximumSize(QtCore.QSize(120, 28))
font = QtGui.QFont()
font.setPointSize(10)
self.Continuous.setFont(font)
self.Continuous.setObjectName("Continuous")
self.Continuous.clicked.connect(self.CaptureCont)
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(10, 440, 118, 21))
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 795, 21))
self.menubar.setObjectName("menubar")
self.menu_File = QtWidgets.QMenu(self.menubar)
self.menu_File.setObjectName("menu_File")
self.menu_Setup = QtWidgets.QMenu(self.menubar)
self.menu_Setup.setObjectName("menu_Setup")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionSave_As = QtGui.QAction("&Save File", self)
self.actionSave_As.setShortcut("Ctrl+S")
self.actionSave_As.setStatusTip('Save File')
self.actionSave_As.triggered.connect(self.saveFileDialog)
self.actionMeasure_Baseline = QtWidgets.QAction(MainWindow)
self.actionMeasure_Baseline.setObjectName("actionMeasure_Baseline")
self.actionMeasure_Baseline.triggered.connect(self.Baseline_meas)
self.actionAbsorption_at_Single_Wavelength = QtWidgets.QAction(MainWindow)
self.actionAbsorption_at_Single_Wavelength.setObjectName("actionAbsorption_at_Single_Wavelength")
self.actionAccumulation = QtWidgets.QAction(MainWindow)
self.actionAccumulation.setObjectName("actionAccumulation")
self.actionAccumulation.triggered.connect(self.AccumulationDialog)
self.menu_File.addAction(self.actionSave_As)
self.menu_Setup.addAction(self.actionMeasure_Baseline)
self.menu_Setup.addAction(self.actionAccumulation)
self.menu_Setup.addAction(self.actionAbsorption_at_Single_Wavelength)
self.menubar.addAction(self.menu_File.menuAction())
self.menubar.addAction(self.menu_Setup.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I would greatly appreciate any help in figuring out where I am going wrong. Thank you.

Python file launched by bash produces error

I have a python script that runs fine when launched on its own.
I want to write a bash script that will run one python script, and then another when the first ends.
Bash script:
#!/bin/bash
python /FILEPATH/FILE1.py ;
python /FILEPATH/FILE2.py
When I execute the bash file, I get this error message:
File "Filename of first python script", line 149
self.label_2.setText(f'Invalid: {input_str}')
File "Filename of second python script", line 139
self.label_2.setText(f'Invalid: {input_str}')
with an accent pointing at the last single quote of both lines.
(The scripts are identical, save for the values contained in the dictionary.
Here is that code
import sys
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import QMovie, QPixmap
from PyQt5.QtWidgets import *
WINDOW_STYLE = '''
background-color:black;
color:white;
'''
class Ui_Widget(QWidget):
# You need to change this
CARD_DICT = {
# PIN: IMAGE_PATH
'1360739516458': 'images/1.png', # Right lung
'1360743335192': 'images/2.png', # Left lung apex
'1360341692930': 'images/3.png', # Left heart
'136073147157207': 'images/4.png', # Spleen
'136075353245': 'images/5.png', # Subxiphoid cardiac
# '136072179130241': 'images/6.png', # Diaphragm?
# '136073133188248': 'images/7.png', # Supra umbilicus
# '136035223197177': 'images/8.png', # right lateral
# '1360341562547': 'images/9.png', # left lateral
# '13607311245156': 'images/10.png', # Sub umbilicus
# the following are for testing purposes only
'60013620412116': 'images/6.png', # Diaphragm?
'13603447120253': 'images/7.png', # Supra umbilicus
'1360341002204': 'images/8.png', # right lateral
'13607217912415': 'images/9.png', # left lateral
'136073209222206': 'images/10.png', # Sub umbilicus
}
def __init__(self):
super(Ui_Widget, self).__init__()
self.setWindowTitle('Simulated Ultrasound')
# Full screen
self.setWindowState(Qt.WindowMaximized)
# No close, minimize and miximaze window button
self.setWindowFlag(Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_StyledBackground, True)
self.setStyleSheet(WINDOW_STYLE)
self.setupUi(self)
def setupUi(self, Widget):
Widget.setObjectName("Widget")
Widget.resize(800, 600)
self.verticalLayout_2 = QtWidgets.QVBoxLayout(Widget)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(Widget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(50)
self.label.setFont(font)
self.label.setFrameShape(QtWidgets.QFrame.NoFrame)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.verticalLayout_2.addLayout(self.gridLayout)
self.lineEdit = QtWidgets.QLineEdit(Widget)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred
)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
self.lineEdit.setSizePolicy(sizePolicy)
self.lineEdit.setMinimumSize(QtCore.QSize(780, 0))
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout_2.addWidget(self.lineEdit)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
self.horizontalLayout.setSpacing(10)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label_2 = QtWidgets.QLabel(Widget)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Maximum
)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())
self.label_2.setSizePolicy(sizePolicy)
self.label_2.setMinimumSize(QtCore.QSize(0, 10))
self.label_2.setObjectName("label_2")
self.horizontalLayout.addWidget(self.label_2)
spacerItem = QtWidgets.QSpacerItem(
40, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum
)
self.horizontalLayout.addItem(spacerItem)
self.pushButton = QtWidgets.QPushButton(Widget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMinimumSize(QtCore.QSize(0, 26))
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
self.verticalLayout_2.addLayout(self.horizontalLayout)
self.retranslateUi(Widget)
QtCore.QMetaObject.connectSlotsByName(Widget)
# I think this is the line to change to make it launch another script
self.pushButton.pressed.connect(Widget.close) # type: ignore
# self.pushButton.pressed.connect(Widget.post_intervention) # type: ignore
# Check every time the text line input changed
self.lineEdit.textChanged.connect(self.submit_pass) # type: ignore
def retranslateUi(self, Widget):
_translate = QtCore.QCoreApplication.translate
Widget.setWindowTitle(_translate("Widget", "Widget"))
self.label.setText(_translate("Widget", "Scan patient to begin"))
self.lineEdit.setPlaceholderText(_translate("Widget", "PIN Phrase"))
self.label_2.setText(_translate("Widget", "Arthur: PRE-intervention"))
self.pushButton.setText(_translate("Widget", "Click here after performing interventions"))
def submit_pass_str(self, input_str):
"""here the application accept user input"""
if input_str in self.CARD_DICT:
self.display_image(self.CARD_DICT[input_str])
self.label_2.setText('')
else:
self.label_2.setText(f'Invalid: {input_str}')
def display_image(self, path):
name, ext = os.path.splitext(path)
if ext and ext.lower() == '.gif':
movie = QMovie(path)
self.label.setMovie(movie)
movie.start()
else:
image = QPixmap(path)
self.label.setPixmap(image)
self.label.setMinimumSize(1, 1)
def submit_pass(self):
"""Usage example using PIN Phrase input form"""
self.submit_pass_str(self.lineEdit.text())
app = QApplication(sys.argv)
window = Ui_Widget()
window.show()
# sys.exit(post_intervention())
sys.exit(app.exec_())

why i pyqt5 tell me this widget does not exist if i know it does?

# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'messagerGUI.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
# ""
from PyQt5 import QtCore, QtGui, QtWidgets
import socket
import threading
class Ui_MainWindow(object):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
header = 12
connections = []
ip = socket.gethostname()
port = 1234
connections_allowed = 3
sock.bind((ip, port))
sock.listen(connections_allowed)
new_message = False
def start(self):
while True:
self.conn, self.addr = self.sock.accept()
threading.Thread(target=self.receive_data, args=[
self.conn], daemon=True).start()
self.connections.append(self.conn)
def receive_data(self, conn):
self.reply = ""
while True:
try:
message_lenth = conn.recv(self.header)
lenth_of_message = message_lenth.decode("utf-8")
if not message_lenth:
break
elif message_lenth:
data = conn.recv(int(lenth_of_message))
self.reply = data.decode("utf-8")
print(self.reply)
self.new_message = True
for connection in self.connections:
if connection != conn:
connection.send(message_lenth.encode("utf-8"))
connection.send(self.reply.encode("utf-8"))
except:
break
def packing_data_lenth(self, text):
return len(text) * 4
def send_data(self, data):
try:
for connection in self.connections:
connection.send(
bytes(str(self.packing_data_lenth(data)), "utf-8"))
connection.send(bytes(data, "utf-8"))
except:
pass
def setupUi(self, MainWindow):
threading.Thread(target=self.start, daemon=True).start()
MainWindow.setObjectName("MainWindow")
MainWindow.resize(499, 367)
MainWindow.setStyleSheet("background-color: #113e4a;")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setContentsMargins(5, 5, 5, 5)
self.horizontalLayout.setSpacing(5)
self.horizontalLayout.setObjectName("horizontalLayout")
self.info = QtWidgets.QWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.info.sizePolicy().hasHeightForWidth())
self.info.setSizePolicy(sizePolicy)
self.info.setMinimumSize(QtCore.QSize(178, 357))
self.info.setStyleSheet("background-color: #429178;\n"
"border-radius: 2px;")
self.info.setObjectName("info")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.info)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.label_3 = QtWidgets.QLabel(self.info)
self.label_3.setObjectName("label_3")
self.verticalLayout_3.addWidget(self.label_3)
spacerItem = QtWidgets.QSpacerItem(
20, 317, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem)
self.horizontalLayout.addWidget(self.info)
self.message_widget()
self.chat_area = QtWidgets.QWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.chat_area.sizePolicy().hasHeightForWidth())
self.chat_area.setSizePolicy(sizePolicy)
self.chat_area.setMinimumSize(QtCore.QSize(306, 0))
self.chat_area.setStyleSheet("background-color: #429178;")
self.chat_area.setObjectName("chat_area")
self.verticalLayout = QtWidgets.QVBoxLayout(self.chat_area)
self.verticalLayout.setContentsMargins(2, 2, 2, 2)
self.verticalLayout.setSpacing(1)
self.verticalLayout.setObjectName("verticalLayout")
self.messages_area = QtWidgets.QScrollArea(self.chat_area)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.MinimumExpanding)
sizePolicy.setHeightForWidth(
self.messages_area.sizePolicy().hasHeightForWidth())
self.messages_area.setSizePolicy(sizePolicy)
self.messages_area.setMinimumSize(QtCore.QSize(0, 259))
self.messages_area.setStyleSheet("background-color: #113e4a;")
self.messages_area.setWidgetResizable(True)
self.messages_area.setObjectName("messages_area")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 300, 316))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.scrollAreaWidgetContents.sizePolicy().hasHeightForWidth())
self.scrollAreaWidgetContents.setSizePolicy(sizePolicy)
self.scrollAreaWidgetContents.setLayoutDirection(QtCore.Qt.LeftToRight)
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(
self.scrollAreaWidgetContents)
self.verticalLayout_2.setSizeConstraint(
QtWidgets.QLayout.SetNoConstraint)
self.verticalLayout_2.setSpacing(6)
self.verticalLayout_2.setObjectName("verticalLayout_2")
spacerItem1 = QtWidgets.QSpacerItem(
20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.MinimumExpanding)
self.verticalLayout_2.addItem(spacerItem1)
self.messages_area.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout.addWidget(self.messages_area)
self.input_area = QtWidgets.QWidget(self.chat_area)
self.input_area.setMinimumSize(QtCore.QSize(0, 30))
self.input_area.setObjectName("input_area")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.input_area)
self.horizontalLayout_2.setContentsMargins(1, 1, 1, 1)
self.horizontalLayout_2.setSpacing(1)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.userInput = QtWidgets.QLineEdit(self.input_area)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.userInput.sizePolicy().hasHeightForWidth())
self.userInput.setSizePolicy(sizePolicy)
self.userInput.setMinimumSize(QtCore.QSize(22, 32))
font = QtGui.QFont()
font.setPointSize(12)
self.userInput.setFont(font)
self.userInput.setStyleSheet("background-color: rgb(17, 62, 74);\n"
"color: #d0e8ce;\n"
"border: 0px;")
self.userInput.setInputMethodHints(QtCore.Qt.ImhNone)
self.userInput.setFrame(True)
self.userInput.setDragEnabled(True)
self.userInput.setPlaceholderText("Type a message")
self.userInput.setObjectName("userInput")
self.horizontalLayout_2.addWidget(self.userInput)
self.sendButton = QtWidgets.QPushButton(self.input_area)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.sendButton.sizePolicy().hasHeightForWidth())
self.sendButton.setSizePolicy(sizePolicy)
self.sendButton.setMinimumSize(QtCore.QSize(12, 32))
font = QtGui.QFont()
font.setPointSize(12)
self.sendButton.setFont(font)
self.sendButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.sendButton.setMouseTracking(True)
self.sendButton.setObjectName("sendButton")
self.sendButton.clicked.connect(self.get_user_input)
self.horizontalLayout_2.addWidget(self.sendButton)
self.verticalLayout.addWidget(self.input_area)
self.horizontalLayout.addWidget(self.chat_area)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
In this part(function message_widget) i get an error:
self.widget = QtWidgets.QWidget(self.scrollAreaWidgetContents)
AttributeError: 'Ui_MainWindow' object has no attribute 'scrollAreaWidgetContents'
Even though i did something similar in the get_user_input function,
i know the code is a mess but the only part that is not working is this part,
the socket server and client are both working properly, i tested printing the
text received in the terminal, so yeah, i wanna know why do i get this error?
def message_widget(self):
self.widget = QtWidgets.QWidget(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.widget.sizePolicy().hasHeightForWidth())
self.widget.setSizePolicy(sizePolicy)
self.widget.setMinimumSize(QtCore.QSize(158, 25))
self.widget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.widget.setStyleSheet(
"background-color: #d35439;\n" "border-radius: 4px;")
self.widget.setObjectName("widget")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.widget)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.label = QtWidgets.QLabel(self.widget)
self.label.setScaledContents(True)
self.label.setObjectName("label")
self.label.text(self.reply)
self.horizontalLayout_3.addWidget(self.label)
self.verticalLayout_2.addWidget(self.widget)
def get_user_input(self):
self.user_msg = self.userInput.text()
threading.Thread(target=self.send_data, args=[
self.user_msg], daemon=True).start()
self.widget_2 = QtWidgets.QWidget(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHeightForWidth(
self.widget_2.sizePolicy().hasHeightForWidth())
self.widget_2.setSizePolicy(sizePolicy)
self.widget_2.setMinimumSize(QtCore.QSize(182, 25))
self.widget_2.setLayoutDirection(QtCore.Qt.RightToLeft)
self.widget_2.setStyleSheet("background-color: rgb(236, 172, 55);\n"
"border-radius: 4px;")
self.widget_2.setObjectName("widget_2")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.widget_2)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.label_2 = QtWidgets.QLabel(self.widget_2)
self.label_2.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_2.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.label_2.setObjectName("label_2")
self.label_2.setText(self.user_msg)
self.horizontalLayout_4.addWidget(self.label_2)
self.verticalLayout_2.addWidget(self.widget_2)
self.userInput.setText("")
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "PadoMessager"))
self.label_3.setText(_translate("MainWindow", "Server"))
self.sendButton.setText(_translate("MainWindow", "Send"))
self.sendButton.setShortcut(_translate("MainWindow", "Return"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
You think it exists, but when you call message_widget() it does not exist yet.
In fact, you are calling that function before this line:
self.scrollAreaWidgetContents = QtWidgets.QWidget()
So, it could work if you put that function at least after creating that widget.
Unfortunately, there are other serious issues with your code.
The most important one is that you are modifying the output of pyuic to create your program, which is highly discouraged (and the WARNING message at the beginning should be a hint).
The python scripts generated from UI files should NEVER be edited, but used as an import in your actual program files. The most obvious reason is that as soon as you want to do some changes in the ui, you'll find yourself in the mess of trying to merge the new generated code with what you've written so far.
To know more about this, read the documentation about using Designer.
Other issues in your code:
threading in Qt should be used with Qt's own QThread as much as possible;
UI objects should never be accessed nor modified by an external thread; to do that you have to use a QThread, and communicate with the main Qt thread using signals and slots;
QLabel.text() does not accept parameters, as it is used to access the text property; to set the text of a label, use setText();

How can I set the sizePolicy of my mainWindow?

I made a simple mainWindow with the help of the qt designer and got the whole code using the pyuic5 option in the cmd.
I added this lineto the main part:
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
to be able to see my window correctly (without this its a whole mass).
In the properties inside qt designer i changed the sizePolicy values to be expanding, but when i try to run my application the sizePolicy is not working, it all stays in the left upper corner.
This is the code i got from the pyuic5:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_CompanyCommanderLogin(object):
def setupUi(self, CompanyCommanderLogin):
CompanyCommanderLogin.setObjectName("CompanyCommanderLogin")
CompanyCommanderLogin.resize(252, 227)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(CompanyCommanderLogin.sizePolicy().hasHeightForWidth())
CompanyCommanderLogin.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(CompanyCommanderLogin)
self.centralwidget.setObjectName("centralwidget")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(10, 10, 231, 171))
self.groupBox.setObjectName("groupBox")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(20, 40, 71, 16))
self.label.setObjectName("label")
self.label_3 = QtWidgets.QLabel(self.groupBox)
self.label_3.setGeometry(QtCore.QRect(20, 70, 41, 16))
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.groupBox)
self.label_4.setGeometry(QtCore.QRect(20, 100, 41, 16))
self.label_4.setObjectName("label_4")
self.lineEdit_x_location = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_x_location.setGeometry(QtCore.QRect(100, 70, 51, 20))
self.lineEdit_x_location.setObjectName("lineEdit_x_location")
self.lineEdit_y_location = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_y_location.setGeometry(QtCore.QRect(100, 100, 51, 20))
self.lineEdit_y_location.setObjectName("lineEdit_y_location")
self.pushButton_login = QtWidgets.QPushButton(self.groupBox)
self.pushButton_login.setGeometry(QtCore.QRect(140, 140, 71, 21))
self.pushButton_login.setStyleSheet("background-color: rgb(0, 209, 255);\n"
"color: rgb(255, 255, 255);\n"
"background-color: rgb(0, 0, 127);")
self.pushButton_login.setObjectName("pushButton_login")
self.comboBox = QtWidgets.QComboBox(self.groupBox)
self.comboBox.setGeometry(QtCore.QRect(100, 40, 51, 21))
self.comboBox.setObjectName("comboBox")
CompanyCommanderLogin.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(CompanyCommanderLogin)
self.menubar.setGeometry(QtCore.QRect(0, 0, 252, 18))
self.menubar.setObjectName("menubar")
CompanyCommanderLogin.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(CompanyCommanderLogin)
self.statusbar.setObjectName("statusbar")
CompanyCommanderLogin.setStatusBar(self.statusbar)
self.retranslateUi(CompanyCommanderLogin)
QtCore.QMetaObject.connectSlotsByName(CompanyCommanderLogin)
def retranslateUi(self, CompanyCommanderLogin):
_translate = QtCore.QCoreApplication.translate
CompanyCommanderLogin.setWindowTitle(_translate("CompanyCommanderLogin", "Company Commander Login"))
self.groupBox.setTitle(_translate("CompanyCommanderLogin", "Login"))
self.label.setText(_translate("CompanyCommanderLogin", "<html><head/><body><p><span style=\" font-size:9pt;\">Company Number:</span></p></body></html>"))
self.label_3.setText(_translate("CompanyCommanderLogin", "<html><head/><body><p><span style=\" font-size:9pt;\">X Location:</span></p></body></html>"))
self.label_4.setText(_translate("CompanyCommanderLogin", "<html><head/><body><p><span style=\" font-size:9pt;\">Y Location:</span></p></body></html>"))
self.pushButton_login.setText(_translate("CompanyCommanderLogin", "Login"))
if __name__ == "__main__":
import sys
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QtWidgets.QApplication(sys.argv)
CompanyCommanderLogin = QtWidgets.QMainWindow()
ui = Ui_CompanyCommanderLogin()
ui.setupUi(CompanyCommanderLogin)
CompanyCommanderLogin.show()
sys.exit(app.exec_())
What could be the problem with the sizePolicy? Is there another way to make my mainWindow the expand?
Picture for example (Here the login is in the left upper corner, I want it to be the whole window size)
As the docs points out:
The size policy of a widget is an expression of its willingness to be resized in various ways, and affects how the widget is treated by the layout engine. Each widget returns a QSizePolicy that describes the horizontal and vertical resizing policy it prefers when being laid out. You can change this for a specific widget by changing its QWidget::sizePolicy property.
The QSizePolicy work only in layouts, and in your case there are none.
So the solution is to create your design using the QXLayout, if you want to use it in Qt Designer you should read the Qt Designer Manual and especially section Using Layouts in Qt Designer.
In this case, since you have not provided the .ui that would allow me to use Qt Designer, I will quickly provide the solution from scratch
from PyQt5 import QtCore, QtGui, QtWidgets
class CompanyCommanderLogin(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.groupbox = QtWidgets.QGroupBox(self.tr("Login"))
self.company_cb = QtWidgets.QComboBox()
sp = self.company_cb.sizePolicy()
sp.setHorizontalPolicy(QtWidgets.QSizePolicy.Expanding)
self.company_cb.setSizePolicy(sp)
self.xlocation_le = QtWidgets.QLineEdit()
self.ylocation_le = QtWidgets.QLineEdit()
self.login_button = QtWidgets.QPushButton(self.tr("Login"))
self.login_button.setStyleSheet(
"background-color: rgb(0, 209, 255);\n"
"color: rgb(255, 255, 255);\n"
"background-color: rgb(0, 0, 127);"
)
font = self.font()
font.setPointSize(9)
self.setFont(font)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QVBoxLayout(central_widget)
lay.addWidget(self.groupbox)
flay = QtWidgets.QFormLayout()
flay.addRow(
self.tr("Company Number:"), self.company_cb,
)
flay.addRow(
self.tr("X Location:"), self.xlocation_le,
)
flay.addRow(
self.tr("Y Location:"), self.ylocation_le,
)
lay = QtWidgets.QVBoxLayout()
lay.addLayout(flay)
lay.addWidget(self.login_button, alignment=QtCore.Qt.AlignHCenter)
lay.addStretch()
self.groupbox.setLayout(lay)
if __name__ == "__main__":
import sys
if hasattr(QtCore.Qt, "AA_EnableHighDpiScaling"):
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QtWidgets.QApplication(sys.argv)
w = CompanyCommanderLogin()
w.show()
sys.exit(app.exec_())

PyQt add a scrollbar to MainWindow

This a recuring question and i've read many topics some helped a bit (python Qt: main widget scroll bar, PyQt: Put scrollbars in this), some not at all (PyQt adding a scrollbar to my main window), I still have problem with the scrollbars. They're not usable, the're 'grey'.
Here is my code (I'm using PyQt5) :
def setupUi(self, Interface):
Interface.setObjectName("Interface")
Interface.resize(1152, 1009)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Interface.sizePolicy().hasHeightForWidth())
Interface.setSizePolicy(sizePolicy)
Interface.setMouseTracking(False)
icon = QtGui.QIcon()
self.centralWidget = QtWidgets.QWidget(Interface)
self.centralWidget.setObjectName("centralWidget")
self.scrollArea = QtWidgets.QScrollArea(self.centralWidget)
self.scrollArea.setGeometry(QtCore.QRect(0, 0, 1131, 951))
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollArea.setEnabled(True)
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1112, 932))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)
self.horizontalLayout.setObjectName("horizontalLayout")
So i would like to put the scrollbars on the main widget, so if the user resizes the main window, the scrollbar appears, and let he move up and down to see child widgets that is outside the smaller window widget, allowing it to move right and left.
Help appreciated !
There are several things wrong with the example code. The main problems are that you are not using layouts properly, and the content widget is not being added to the scroll-area.
Below is a fixed version (the commented lines are all junk, and can be removed):
def setupUi(self, Interface):
# Interface.setObjectName("Interface")
# Interface.resize(1152, 1009)
# sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
# sizePolicy.setHorizontalStretch(0)
# sizePolicy.setVerticalStretch(0)
# sizePolicy.setHeightForWidth(Interface.sizePolicy().hasHeightForWidth())
# Interface.setSizePolicy(sizePolicy)
# Interface.setMouseTracking(False)
# icon = QtGui.QIcon()
self.centralWidget = QtWidgets.QWidget(Interface)
# self.centralWidget.setObjectName("centralWidget")
layout = QtWidgets.QVBoxLayout(self.centralWidget)
self.scrollArea = QtWidgets.QScrollArea(self.centralWidget)
# self.scrollArea.setGeometry(QtCore.QRect(0, 0, 1131, 951))
# self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
# self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
# self.scrollArea.setWidgetResizable(True)
# self.scrollArea.setObjectName("scrollArea")
# self.scrollArea.setEnabled(True)
layout.addWidget(self.scrollArea)
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1112, 932))
# self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
layout = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)
# self.horizontalLayout.setObjectName("horizontalLayout")
# add child widgets to this layout...
Interface.setCentralWidget(self.centralWidget)
The scrollbars are grayed out because you made them always visible by setting the scrollbar policy to Qt.ScrollBarAlwaysOn but actually there is no content to be scrolled so they are disabled. If you want scrollbars to appear only when they are needed you need to use Qt.ScrollBarAsNeeded.
There is no content to be scrolled because there is only 1 widget in the QHBoxLayout (see self.scrollAreaWidgetContents). Also if this method is being executed from a QMainWindow you also have an error when setting the central widget: self.centralWidget is a method to retrieve the central widget. It's working because you are overwriting it with a QWidget instance (and I believe python allows you to do that). To correctly set the central widget you need to use setCentralWidget() in QMainWindow.
def setupUi(self, Interface):
Interface.setObjectName("Interface")
Interface.resize(1152, 1009)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Interface.sizePolicy().hasHeightForWidth())
Interface.setSizePolicy(sizePolicy)
Interface.setMouseTracking(False)
icon = QtGui.QIcon()
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.scrollArea = QtWidgets.QScrollArea()
self.scrollArea.setGeometry(QtCore.QRect(0, 0, 1131, 951))
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollArea.setEnabled(True)
self.horizontalLayout.addWidget(self.scrollArea)
centralWidget = QWidgets.QWidget()
centralWidget.setObjectName("centralWidget")
centralWidget.setLayout(self.horizontalLayout)
self.setCentralWidget(centralWidget)
I left Interface out since I don't know what it is, but the rest should be ok.

Categories