pyqt5 how to fix image size in VBox? - python

i created image with label in VBox but the issue is the size of the image is not same as the VBox size.
when i tried to fix it the image goes to the right
this is my code:-
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
import requests
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Image")
self.resize(1274, 906)
self.ititUI()
def ititUI(self):
self.anime = QWidget(self)
self.anime.move(20, 20)
self.vAnime = QVBoxLayout(self.anime)
self.anime.setFixedSize(272, 456)
self.anime.setObjectName("anime")
self.limage = QLabel(self)
image = QImage()
image.loadFromData(requests.get('https://64.media.tumblr.com/853aebaad6d38097da49e8986b8458b9/tumblr_odewby7Kr51szm930o1_1280.jpg').content)
self.limage.setPixmap(QPixmap(image))
self.limage.setScaledContents(True)
self.limage.setFixedSize(272, 384)
self.lname = QLabel("Image Text",self)
self.lname.setWordWrap(True)
self.lname.setObjectName('lname')
self.vAnime.addWidget(self.limage)
self.vAnime.addWidget(self.lname)
self.lname.setAlignment(Qt.AlignHCenter|Qt.AlignTop)
app = QApplication(sys.argv)
app.setStyleSheet(open("style.stylesheet", "r").read())
win = MyWindow()
win.show()
sys.exit(app.exec_())

Related

Add icon to QTextEdit | Python | PyQt5 | QtWidgets.QTextEdit [duplicate]

I am trying to print text into QTextEdit field but for some reason the image shows up first.
Here is my code:
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
textEdit = QtGui.QTextEdit('',self)
textEdit.setGeometry(QtCore.QRect(300, 300, 640, 480))
textEdit.move(0, 0)
self.setGeometry(300, 300, 640, 480)
img = QImage('image.png','PNG')
cursor = QTextCursor(textEdit.document())
cursor.insertText("Hello World")
cursor.insertImage(img)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
It looks like this in my QTextEdit field:
some image
Hello World
But I want it to look like:
Hello World
some image
The image is on top of the string. Also, there's a big ugly cursor as tall as my image (500 pixels high). What code should I use so a) the string prints before the image and b) the cursor is hidden after I'm done inserting?
You'll need to position the cursor where you want to insert the image. Checkout this code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtGui, QtCore
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.pushButtonImage = QtGui.QPushButton(self)
self.pushButtonImage.setText("Insert Image!")
self.pushButtonImage.clicked.connect(self.on_pushButtonImage_clicked)
self.textEditImage = QtGui.QTextEdit(self)
self.textEditImage.setPlainText("Insert an image here:")
self.layoutVertical = QtGui.QVBoxLayout(self)
self.layoutVertical.addWidget(self.pushButtonImage)
self.layoutVertical.addWidget(self.textEditImage)
def on_pushButtonImage_clicked(self):
filePath = QtGui.QFileDialog.getOpenFileName(
self,
"Select an image",
".",
"Image Files(*.png *.gif *.jpg *jpeg *.bmp)"
)
if not filePath.isEmpty():
self.insertImage(filePath)
def insertImage(self, filePath):
imageUri = QtCore.QUrl(QtCore.QString("file://{0}".format(filePath)))
image = QtGui.QImage(QtGui.QImageReader(filePath).read())
self.textEditImage.document().addResource(
QtGui.QTextDocument.ImageResource,
imageUri,
QtCore.QVariant(image)
)
imageFormat = QtGui.QTextImageFormat()
imageFormat.setWidth(image.width())
imageFormat.setHeight(image.height())
imageFormat.setName(imageUri.toString())
textCursor = self.textEditImage.textCursor()
textCursor.movePosition(
QtGui.QTextCursor.End,
QtGui.QTextCursor.MoveAnchor
)
textCursor.insertImage(imageFormat)
# This will hide the cursor
blankCursor = QtGui.QCursor(QtCore.Qt.BlankCursor)
self.textEditImage.setCursor(blankCursor)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())

Background picture in QMainwindow PyQt5

I'm trying to get a background image to my mainwindow but i can't get it to work properly.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
from PyQt5.QtGui import QIcon
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSvg import *
from PyQt5.QtWidgets import *
from abc import abstractmethod
class App(QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.title = 'Title'
self.left = 500
self.top = 500
self.width = 440
self.height = 280
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# ...
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
#view = TableScene(ex)
ex.show()
sys.exit(app.exec_())
I've tried different kinds of methods but none of them works as it should.
I found the following code as a solution from another topic but it just gives me a black background and the rest of the widgets get laggy.
oImage = QImage("table.png")
sImage = oImage.scaled(QSize(440, 280))
palette = QPalette()
palette.setBrush(QPalette.Window, QBrush(sImage))
self.setPalette(palette)
I don't know if the whole window gets laggy or what really happens but the picture below is a screenshot of a part of the window using the code above, and as you can see it gets all black and the slider shows all the previous position it has been on, sort of laggy anyways.
I've also tried the setStyleSheet but I don't know if it's my syntax that's wrong or if it's a faulty way of doing it. Does anyone know a way of doing it correctly?
EDIT
This is my current window:
This is the picture I'm trying to implement as a background to my current window, the picture called "table.png" :
This is a visualization of what I'm trying to do, and this is made in paint since I don't know how to do it correctly:
And this is what I get if i use the code from the other topic:
One of the possible reasons why a black background appears is that QImage is null. And a QImage is null because the image is invalid or because the image path is incorrect. In this case I think it is the second case since the OP uses a relative path that is prone to errors. The solution is to build the absolute path using the script information such as its location:
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class App(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.initUI()
def initUI(self):
self.setWindowTitle("Title")
self.setGeometry(500, 500, 440, 280)
oImage = QtGui.QImage(os.path.join(CURRENT_DIR, "table.png"))
sImage = oImage.scaled(QtCore.QSize(440, 280))
palette = QtGui.QPalette()
palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(sImage))
self.setPalette(palette)
pushbutton = QtWidgets.QPushButton("test", self)
pushbutton.move(100, 100)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
Note: The image provided by the OP has extension .jpg but the one indicated by code is .png, maybe "imgur" has changed the extension.
Note: If the window is resized manually, the following behavior will be observed:
So for this there are 2 possible solutions depending on the developer's criteria:
Set a fixed size: self.setFixedSize(440, 280)
Adapt the image to the size of the window:
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class App(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.initUI()
def initUI(self):
self.setWindowTitle("Title")
self.setGeometry(500, 500, 440, 280)
pushbutton = QtWidgets.QPushButton("test", self)
pushbutton.move(100, 100)
self.oImage = QtGui.QImage(os.path.join(CURRENT_DIR, "table.png"))
# or QPixmap
# self.oPixmap = QtGui.QPixmap(os.path.join(CURRENT_DIR, "table.png"))
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawImage(self.rect(), self.oImage)
# or QPixmap
# painter.drawPixmap(self.rect(), self.oPixmap)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
or
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class App(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.initUI()
def initUI(self):
self.setWindowTitle("Title")
self.setGeometry(500, 500, 440, 280)
pushbutton = QtWidgets.QPushButton("test", self)
pushbutton.move(100, 100)
self.setStyleSheet(
"""
QMainWindow{
border-image: url(%s) 0 0 0 0 stretch stretch
}
"""
% os.path.join(CURRENT_DIR, "table.png")
)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())

PyQt5: How to place a QPixmap on top of another QPixmap?

I would like to place a QPixmap on another QPixmap. Both have the same size, so I would just like to make an overlay. The overlay image has a transparent elipse in the middle. I figure they should be QPixmap format, however I dont know how to place them on top of each other and keep them in place when resizing the window. This is my code displaying how my background images are placed. I have attached a image explaining what i want.
import sys
from PyQt5 import QtGui ,QtWidgets, uic
from PyQt5.QtCore import Qt
class Ergolab(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(Ergolab, self).__init__(*args, **kwargs)
# Load the UI Page
self.ui = uic.loadUi("mainwindow.ui",self)
self.pixmap1 = QtGui.QPixmap('C:/Users/Frede/Desktop/img1.jpg')
self.shoflexLLabel.setPixmap(self.pixmap1.scaled(self.shoflexLLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
self.shoflexLLabel.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.shoflexLLabel.setMinimumSize(150, 150)
self.shoflexLLabel.resize(800, 600)
self.pixmap2 = QtGui.QPixmap('C:/Users/Frede/Desktop/img2.jpg')
self.shoflexRLabel.setPixmap(self.pixmap2.scaled(self.shoflexRLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
self.shoflexRLabel.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.shoflexRLabel.setMinimumSize(150, 150)
self.shoflexRLabel.resize(800, 600)
def resizeEvent(self, event):
scaledSize = self.shoflexLLabel.size()
if not self.shoflexLLabel.pixmap() or scaledSize != self.shoflexLLabel.pixmap().size():
self.updateLabel()
def updateLabel(self):
self.shoflexLLabel.setPixmap(self.pixmap1.scaled(
self.shoflexLLabel.size(), Qt.KeepAspectRatio,
Qt.SmoothTransformation))
self.shoflexRLabel.setPixmap(self.pixmap2.scaled(
self.shoflexRLabel.size(), Qt.KeepAspectRatio,
Qt.SmoothTransformation))
def main():
app = QtWidgets.QApplication(sys.argv)
main = Ergolab()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
This is the result I would like:
You must use QPainter by setting the circle as a clip path:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
label = QtWidgets.QLabel()
self.setCentralWidget(label)
base_pixmap = QtGui.QPixmap("background.png")
overlay_pixmap = QtGui.QPixmap("overlay.png")
radius = 300
r = QtCore.QRectF()
r.setSize(radius * QtCore.QSizeF(1, 1))
r.moveCenter(base_pixmap.rect().center())
path = QtGui.QPainterPath()
path.addEllipse(r)
painter = QtGui.QPainter(base_pixmap)
painter.setRenderHints(
QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform
)
painter.setClipPath(path, QtCore.Qt.IntersectClip)
painter.drawPixmap(QtCore.QPoint(), overlay_pixmap)
painter.end()
label.setPixmap(base_pixmap)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

How to draw a gray square(200*100) on a white area(1280*720) with QGraphicsView in pyqt5?

guys,what i want is to draw a gray square(200*100) on a white area(1280*720),But I don't know how to do it with QGraphicsView, can you help me?
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class AAA(QGraphicsView):
def __init__(self):
super().__init__()
self.resize(1280, 720)
self.setStyleSheet('background:white')
self.show()
Xscene = QGraphicsScene()
self.setScene(Xscene)
gray_square=qDrawPlainRect(200,100)
Xscene.addItem(gray_square)
A = QApplication(sys.argv)
aaa = AAA()
A.exec_()
You were actually pretty close. Try the following.
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class AAA(QGraphicsView):
def __init__(self):
super().__init__()
self.resize(1280, 720)
self.setStyleSheet('background:white')
self.show()
Xscene = QGraphicsScene()
self.setScene(Xscene)
# gray_square=qDrawPlainRect(200,100)
gray_square = QGraphicsRectItem(0, 0, 200, 100)
gray_square.setPen(Qt.gray)
gray_square.setBrush(QBrush((Qt.gray)))
Xscene.addItem(gray_square)
A = QApplication(sys.argv)
aaa = AAA()
A.exec_()

PyQt - Toggle Frame Resize Push Button

I am having a problem with resizing the frame based on the clicking of a single button. I have a blank window with a single push button called pushButton in my ui file. I would like that whenever this button is pressed, the dimensions of the MainWindow are changed, however the resizing only happens one time. The original dimensions are 640 by 480.
What I am doing incorrectly in the run_resize function? Thanks!
The code is as follows.
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.uic import loadUiType
qtCreatorFile = 'my_gui.ui'
Ui_MainWindow, QtBaseClass = loadUiType(qtCreatorFile)
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.setFixedSize(self.size())
self.frame = QFrame()
self.pushButton.clicked.connect(self.run_resize)
def run_resize(self):
if self.frame.height() == 480:
self.setMinimumSize(640, 150)
self.resize(640, 150)
else:
self.setMinimumSize(640, 480)
self.resize(640, 480)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = main_window()
w.show()
sys.exit(app.exec_())
You have to check the condition on the QMainWindow, here is a working example :
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.uic import loadUiType
qtCreatorFile = 'my_gui.ui'
Ui_MainWindow, QtBaseClass = loadUiType(qtCreatorFile)
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.setFixedSize(self.size())
self.pushButton.clicked.connect(self.run_resize)
def run_resize(self):
if self.height() == 480:
self.setMinimumSize(640, 150)
self.resize(640, 150)
else:
self.setMinimumSize(640, 480)
self.resize(640, 480)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

Categories

Resources