How do I align centre image horizontally in PyQt5? - python-3.x

I'm working on my college project, I want to align an Image to centre Horizontally, I tried many thing but not find solution. Here is my code:
from PyQt5.QtGui import QPalette, QLinearGradient, QColor, QBrush, QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
import sys
from PyQt5 import QtGui
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.acceptDrops()
self.setWindowTitle("Mask Detection")
self.setWindowIcon(QtGui.QIcon('img.png'))
self.setGeometry(0, 0, 400, 300)
self.label = QLabel(self)
self.label.setAlignment(Qt.AlignCenter)
self.pixmap = QPixmap('PBL.png')
self.label.setPixmap(self.pixmap)
self.label.resize(self.pixmap.width(),
self.pixmap.height())
self.show()
App = QApplication(sys.argv)
window = Window()
p = QPalette()
gradient = QLinearGradient(0, 0, 0, 400)
gradient.setColorAt(0.0, QColor(56, 93, 166))
gradient.setColorAt(1.0, QColor(10, 123, 146))
p.setBrush(QPalette.Window, QBrush(gradient))
window.setPalette(p)
sys.exit(App.exec())

The alignment is with respect to the geometry of the element itself, and since the geometry of the QLabel has the same size as the QPixmap then it will not make a difference. The solution is to make the geometry of the QLabel be the same as the window and that can be done by setting it in the centralWidget:
self.setCentralWidget(self.label)

Related

PySide6 Rounded Border Window

I am trying to create a frameless round-corner window using QWidget. I have tried using border-radius in Stylesheet but it's not working.
Here is the code:
from PySide6.QtCore import Qt, QSize
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
class MainWidget(QWidget):
def __init__(self):
super().__init__()
self.setWindowFlag(Qt.FramelessWindowHint)
self.setFixedSize(QSize(400, 400))
self.setStyleSheet("""
MainWidget {
border-radius: 25px;
background: red;
}
""")
self.vertical_layout = QVBoxLayout()
self.button = QPushButton('Exit')
self.button.clicked.connect(lambda: self.close())
self.vertical_layout.addWidget(self.button, alignment=Qt.AlignCenter)
self.setLayout(self.vertical_layout)
app = QApplication([])
widget = MainWidget()
widget.show()
app.exec()
This gives the following result:
If I use the Masking technique then it is not Anti-Aliased and produces blurred corners.
Any help will be appreciated!

Set scroll area initially moved

I need to create a big widget inside a scroll area and initially set both sliders in the middle of the bar. The scroll bar does not work, the widgets are not well connected I think.
MRE:
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget
import sys
class Diedrico(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
# Draws stuff
class UiVentana(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(UiVentana, self).__init__(parent)
ventana.resize(1500, 1015)
ventana.setFixedSize(1500, 1015)
self.widget_central = QtWidgets.QWidget(ventana)
scrol = QtWidgets.QScrollArea(self.widget_central)
scrol.setWidgetResizable(True)
scrol.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
scrol.setGeometry(QtCore.QRect(1010, 510, 470, 460))
self.Diedrico = Diedrico(scrol)
self.Diedrico.setGeometry(QtCore.QRect(0, 0, 1000, 1000))
# This widget should be big enough to use the scroll bar, but it does not work
ventana.setCentralWidget(self.widget_central)
ventana.show()
if __name__ == "__main__":
app = QtWidgets.QApplication([])
ventana = QtWidgets.QMainWindow()
ui = UiVentana()
sys.exit(app.exec_())
It seems that the problem comes from scrol.setWidgetResizable(True), which seems to resize the content... setting this to False worked for me.
Also, to center the scrollbar, there are a few options, like setting the value of the verticalScrollBar or using ensureVisible(x, y).
A working solution:
from PyQt5 import QtCore, QtWidgets
import sys
class UiVentana(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(UiVentana, self).__init__(parent)
self.setupUi()
self.label.setGeometry(QtCore.QRect(10, 0, 282, 331))
self.label.setText("this is a long text\n" * 100)
self.scrollArea.verticalScrollBar().setValue(300)
def setupUi(self):
self.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(self)
self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(470, 330, 301, 211))
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollArea.setWidgetResizable(False)
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 282, 10000))
self.label = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.setCentralWidget(self.centralwidget)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ui = UiVentana()
ui.show()
sys.exit(app.exec_())

PyQt5 MainWindow get postion relative to screen

Simple QMainWindow implementation and too much time googling I need to know what the XY coordinates for the main window are relative to the screen. This implementation always shows 0,0:
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class TestReportsApp(QMainWindow):
def __init__(self, parent=None):
super(TestReportsApp, self).__init__(parent)
loadUi('test.ui', self)
#pyqtSlot()
def showEvent(self, e):
print(self.geometry())
app = QApplication(sys.argv)
mainWin = TestReportsApp()
mainWin.show()
sys.exit(app.exec_())
How do I get the coordinates of the top-left XY position of the main window relative to the screen?

QMainWindow vs QWidget

I can't find good explanations about the different usage of QMainWindow vs. QWidget in PyQt5 (and Qt in general, I guess). From what I've read, QMainWindow inherits from QWidget, so should be able to do everything QWidget can and more. But when I try to convert an example I've found from QWidget into QMainWindow, the layout gets screwed up.
The example I'm trying to work off is from https://www.tutorialspoint.com/pyqt/pyqt_qstackedwidget.htm. (My GUI will have a StackedWidget as central widget, with a sidepanel for navigation, so getting this example to work in a QMainWidget would be a great basis for my own code.)
PyQT5-converted and slightly shortened version:
#!/usr/bin/env python3
import sys
from PyQt5.QtWidgets import (QApplication, QFormLayout, QLabel, QRadioButton, QCheckBox,
QListWidget, QStackedWidget, QLineEdit,
QHBoxLayout, QGridLayout
)
from PyQt5.Qt import QWidget, QMainWindow
class StackedExample(QMainWindow):
def __init__(self):
super(stackedExample, self).__init__()
self.leftlist = QListWidget ()
self.leftlist.insertItem (0, 'Contact' )
self.leftlist.insertItem (1, 'Personal' )
self.stack1 = QWidget()
self.stack2 = QWidget()
self.stack1UI()
self.stack2UI()
self.Stack = QStackedWidget (self)
self.Stack.addWidget (self.stack1)
self.Stack.addWidget (self.stack2)
grid = QGridLayout()
self.setLayout(grid)
grid.addWidget(self.leftlist,0,0)
grid.addWidget(self.Stack,0,1)
self.leftlist.currentRowChanged.connect(self.display)
self.resize(300,100)
self.show()
def stack1UI(self):
layout = QFormLayout()
layout.addRow("Name",QLineEdit())
layout.addRow("Address",QLineEdit())
self.stack1.setLayout(layout)
def stack2UI(self):
layout = QFormLayout()
sex = QHBoxLayout()
sex.addWidget(QRadioButton("Male"))
sex.addWidget(QRadioButton("Female"))
layout.addRow(QLabel("Sex"),sex)
layout.addRow("Date of Birth",QLineEdit())
self.stack2.setLayout(layout)
def display(self,i):
self.Stack.setCurrentIndex(i)
def main():
app = QApplication(sys.argv)
ex = StackedExample()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
This code worked fine while it was based on QWidget, but when it's based on QMainWidget (like in the above version), everything gets crammed into the upper left corner.
What changes are neccessary to show a layout that works for QWidget in a QMainWindow?
A QMainWindow must have a central widget to display correctly. You need to define a central widget and then add any layouts to it instead of the main window.
class StackedExample(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.leftlist = QListWidget()
self.leftlist.insertItem(0, 'Contact' )
self.leftlist.insertItem(1, 'Personal' )
self.central_widget = QWidget() # define central widget
self.setCentralWidget(self.central_widget) # set QMainWindow.centralWidget
self.stack1 = QWidget()
self.stack2 = QWidget()
self.stack1UI()
self.stack2UI()
self.Stack = QStackedWidget (self)
self.Stack.addWidget (self.stack1)
self.Stack.addWidget (self.stack2)
grid = QGridLayout()
self.centralWidget().setLayout(grid) # add the layout to the central widget
grid.addWidget(self.leftlist,0,0)
grid.addWidget(self.Stack,0,1)
self.leftlist.currentRowChanged.connect(self.display)
self.resize(300,100)
self.show()
There are also other areas besides centralWidget defined for a QMainWindow. Here is the documentation for QMainWindow. It explains this in more detail.

PyQt5 - Add image in background of MainWindow layout

New to PyQt5... Here is a very basic question.
I would like to add an image inside the layout of a widget. This widget is the Main Window / root widget of my application. I use the following code, but I get an error message.
import sys
from PyQt5.QtGui import QImage
from PyQt5.QtWidgets import *
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(300,300,300,220)
self.setWindowTitle("Hello !")
oImage = QImage("backgound.png")
oLayout = QVBoxLayout()
oLayout.addWidget(oImage)
self.setLayout(oLayout)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
oMainwindow = MainWindow()
sys.exit(app.exec_())
TypeError: QBoxLayout.addWidget(QWidget, int stretch=0, Qt.Alignment alignment=0): argument 1 has unexpected type 'QImage'
Apparently a QLayoutWidget does not accept a QImage as an input. Is there a workaround to have an image appear as a brackground in a QWidget ?
The QVBoxLayout class lines up widgets vertically.
documentation QVBoxLayout
QImage is no widget.
on many widgets e.g. QmainWindow, QLabel you can use
widget.setStyleSheet(„ background-image: url(backgound.png);“)
on my machine this doesn't work with QWidget. In this case you can use the following rewrite of your code:
import sys
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QImage, QPalette, QBrush
from PyQt5.QtWidgets import *
class MainWindow(QWidget):
def __init__(self):
QWidget.__init__(self)
self.setGeometry(100,100,300,200)
oImage = QImage("test.png")
sImage = oImage.scaled(QSize(300,200)) # resize Image to widgets size
palette = QPalette()
palette.setBrush(QPalette.Window, QBrush(sImage))
self.setPalette(palette)
self.label = QLabel('Test', self) # test, if it's really backgroundimage
self.label.setGeometry(50,50,200,50)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
oMainwindow = MainWindow()
sys.exit(app.exec_())

Resources