Pyside6 shearing PDF file on window resize - qt

I'm using QT (PySide) to view PDFs (using the PyMuPDF library) but when I resize I get a shearing artifact.
Like this:
Here is a minimal example:
import sys
import fitz
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow, QScrollArea
from PySide6.QtGui import QPixmap, QImage
from PySide6.QtCore import Qt
class PDFWindow(QMainWindow):
def __init__(self, filename):
super().__init__()
# Open the PDF and get the first page
self.pdf_doc = fitz.open(filename)
self.page = self.pdf_doc[0]
# Create a QLabel to hold the rendered page
self.label = QLabel()
self.label.setAlignment(Qt.AlignCenter)
# Create a QScrollArea to hold the label
self.scroll_area = QScrollArea()
self.scroll_area.setWidget(self.label)
self.scroll_area.setWidgetResizable(True)
self.setCentralWidget(self.scroll_area)
# Render the page and set it as the pixmap for the label
self.render_page()
# Connect the windowResized signal to the render_page function
self.resizeEvent = self.render_page
def render_page(self, event=None):
zoom = 1
if event is not None:
bound = self.page.bound()
page_width, page_height = bound.width, bound.height
zoom = min(event.size().width() / page_width,
event.size().height() / page_height)
pixmap = self.page.get_pixmap(matrix=fitz.Matrix(zoom, zoom),
colorspace='rgb')
image = QImage(pixmap.samples, pixmap.width, pixmap.height,
QImage.Format_RGB888)
cur_pixmap= QPixmap.fromImage(image)
self.label.setPixmap(cur_pixmap)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = PDFWindow("example.pdf")
window.show()
sys.exit(app.exec())

Related

qt: qlayout do not correctly add widget

I want do dynamically change the layout in Qt. For example, I want to change the QHBoxLayout to QVBoxLayout through a button. My test code is:
from PyQt5.QtWidgets import *
import sys
class SubWidget(QWidget):
def __init__(self):
super().__init__()
self.lay = QHBoxLayout()
self.label1 = QLabel('left')
self.label2 = QLabel('right')
self.lay.addWidget(self.label1)
self.lay.addWidget(self.label2)
self.setLayout(self.lay)
def change(self):
self.lay.removeWidget(self.label1)
self.lay.removeWidget(self.label2)
self.lay = QVBoxLayout()
self.setLayout(self.lay)
self.lay.addWidget(self.label2)
self.lay.addWidget(self.label1)
class Widget(QWidget):
def __init__(self):
super().__init__()
lay = QVBoxLayout()
self.btn = QPushButton('change layout')
self.btn.clicked.connect(self.btnClick)
self.subWidget = SubWidget()
lay.addWidget(self.btn)
lay.addWidget(self.subWidget)
self.setLayout(lay)
def btnClick(self, check=False):
self.subWidget.change()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Widget()
win.show()
app.exec_()
The code output GUI is:
And I hope it change to the following picture after click change layout button:
Any suggestion is appreciated~~~
The point of the solution is
Make sure old layout is deleted, included both python wrapping reference and core Qt object, that's for deleteLater() is used.
Make sure new layout is assigned strictly after old was deleted, that's for need to use destroyed()-switchlayout() signal-slot chain.
I reproduced example with PySide6 (don't forget to switch on your version of PyQt or PySide package):
# from PyQt5.QtWidgets import *
from PySide6.QtWidgets import *
import sys
class SubWidget(QWidget):
def __init__(self):
super().__init__()
self.lay = QVBoxLayout()
self.label1 = QLabel('left')
self.label2 = QLabel('right')
self.lay.addWidget(self.label1)
self.lay.addWidget(self.label2)
self.setLayout(self.lay)
def change(self):
self.lay.removeWidget(self.label1)
self.lay.removeWidget(self.label2)
self.lay.deleteLater()
self.lay.destroyed.connect(self.switchlayout)
def switchlayout(self):
# print("***destroyed")
self.lay = QHBoxLayout()
self.lay.addWidget(self.label2)
self.lay.addWidget(self.label1)
self.setLayout(self.lay)
self.adjustSize()
class Widget(QWidget):
def __init__(self):
super().__init__()
lay = QVBoxLayout()
self.btn = QPushButton('change layout')
self.btn.clicked.connect(self.btnClick)
self.subWidget = SubWidget()
lay.addWidget(self.btn)
lay.addWidget(self.subWidget)
self.setLayout(lay)
def btnClick(self, check=False):
self.subWidget.change()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Widget()
win.show()
app.exec_()

Resize QDialog when RadioButton is Checked PyQt

not so many experience at all with pyqt..
I have designed an UI with Qt Designer with 2 Radiobuttons.
Depending on the RadioButton selected some widgets are visible and other not. What I'm not trying to do is to resize automatically the layout of the dialog depending on how many widgets are visible in the UI.
The question is very similar to this one . Here the extract of the code that might be helpful to understand the problem (I know it is just a piece of the code, but the entire dialog is pretty long):
class MyDialog(QDialog, FORM_CLASS):
..........
# connect the radioButton with a function that reloads the UI
self.radioSingle.toggled.connect(self.refreshWidgets)
.....
# dictionary with all the widgets and the values
self.widgetType = {
self.cmbModelName: ['all'],
self.cmbGridLayer: ['all'],
self.cmbRiverLayer: ['all'],
self.lineNewLayerEdit: ['all'],
self.lineLayerNumber: ['single']
}
# function that refresh the UI with the correct widgets depending on the radiobutton selected
def refreshWidgets(self, idx):
'''
refresh UI widgets depending on the radiobutton chosen
'''
tp = self.radioSingle.isChecked()
for k, v in self.widgetType.items():
if tp:
if 'all' or 'single' in v:
active = True
k.setEnabled(active)
k.setVisible(active)
else:
active = 'all' in v
k.setEnabled(active)
k.setVisible(active)
# attempt to resize the Dialog
self.setSizeConstraint()
Surely the code could be improved (not so skilled with code writing)...
You just gotta set_up your UI to resize when it's needed.
There is a lot of more beautiful way to do this, but here is a simple and fast example:
You just have to define your layout to behave the way you want. If you make use of Minimum and Maximum size it'll resize as you need.
You could also have your own personalized buttons, widgets, .... you would have a cleaner code.
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QRadioButton
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget
class CustomDialog(QDialog):
w_container = None
v_layout_container = None
v_scroll_area = None
v_layout_preview = None
def __init__(self):
"""Init UI."""
super(CustomDialog, self).__init__()
self.init_ui()
def init_ui(self):
"""Init all ui object requirements."""
self.r1 = QRadioButton("smaller")
self.r2 = QRadioButton("bigger")
style = "background: green;"
size = [200, 50]
self.small_size = [200, 250]
self.big_size = [200, 500]
self.resize(200,200)
self.w1 = QWidget()
self.w2 = QWidget()
self.w3 = QWidget()
self.w4 = QWidget()
self.w5 = QWidget()
self.w6 = QWidget()
self.w1.setStyleSheet(style)
self.w2.setStyleSheet(style)
self.w3.setStyleSheet(style)
self.w4.setStyleSheet(style)
self.w5.setStyleSheet(style)
self.w6.setStyleSheet(style)
self.w1.setFixedSize(size[0], size[1])
self.w2.setFixedSize(size[0], size[1])
self.w3.setFixedSize(size[0], size[1])
self.w4.setFixedSize(size[0], size[1])
self.w5.setFixedSize(size[0], size[1])
self.w6.setFixedSize(size[0], size[1])
self.full_container = QVBoxLayout()
self.full_container.setContentsMargins(0,0,0,0)
self.radio_widget = QWidget()
self.radio_widget.setFixedSize(200, 50)
self.radio_container = QHBoxLayout()
self.radio_container.setContentsMargins(0,0,0,0)
self.widget_widget = QWidget()
self.widget_container = QVBoxLayout()
self.radio_widget.setLayout(self.radio_container)
self.widget_widget.setLayout(self.widget_container)
self.full_container.addWidget(self.radio_widget)
self.full_container.addWidget(self.widget_widget)
self.radio_container.addWidget(self.r1)
self.radio_container.addWidget(self.r2)
self.widget_container.addWidget(self.w1)
self.widget_container.addWidget(self.w2)
self.widget_container.addWidget(self.w3)
self.widget_container.addWidget(self.w4)
self.widget_container.addWidget(self.w5)
self.widget_container.addWidget(self.w6)
self.setLayout(self.full_container)
self.r1.setChecked(True)
def paintEvent(self, event):
if self.r1.isChecked():
self.w4.hide()
self.w5.hide()
self.w6.hide()
self.setFixedSize(self.small_size[0],self.small_size[1])
elif self.r2.isChecked():
self.w4.show()
self.w5.show()
self.w6.show()
self.setFixedSize(self.big_size[0], self.big_size[1])
self.full_container.update()
super(CustomDialog, self).paintEvent(event)
def run():
app = QApplication(sys.argv)
GUI = CustomDialog()
GUI.show()
sys.exit(app.exec_())
run()
Observe that I'm using PyQt5, so if you need you just gotta change your imports to the version you are using.

I can't see QLabel and QLineEdit widgets in my QMainWindow in Python2

I wrote this code and I don't understand why widgets QLabel and QLineEdit don't show up? Do I have to put them in another class? It's Python2.7 and PySide.
This is how a window looks like when I run the code:
#!/usr/bin/env python
# coding: utf-8
import sys
import crypt
from PySide import QtGui
class MyApp(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MyApp, self).__init__(parent)
self.initui()
def initui(self):
# main window size, title and icon
self.setMinimumSize(500, 350)
self.setWindowTitle("Calculate a password hash in Linux")
# lines for entering data
self.saltLabel = QtGui.QLabel("Salt:")
self.saltLine = QtGui.QLineEdit()
self.saltLine.setPlaceholderText("e.g. $6$xxxxxxxx")
# set layout
grid = QtGui.QGridLayout()
grid.addWidget(self.saltLabel, 0, 0)
grid.addWidget(self.saltLine, 1, 0)
self.setLayout(grid)
# show a widget
self.show()
def main():
app = QtGui.QApplication(sys.argv)
instance = MyApp()
instance.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
How about using a QWidget as centralWidget
widget = QWidget()
widget.setLayout(grid)
#add your widgets and...
self.setCentralWidget(widget)
and you don't need to call show() since you do in your __main__
It's up to the owner but i would recommend sublassing a QWidget and leave your QMainWindow instance as concise as possible. An implementation could be:
class MyWidget(QtGui.QWidget):
def __init__(self, *args):
QtGui.QWidget.__init__(self, *args)
grid = QtGui.QGridLayout()
#and so on...
and use this as widget in your QMainWindow instance. This increases readability and maintainability and reusability a lot :)

QMovie setting filename second time wont work

I am setting the Initial Movie File like this:
self.movie = QMovie("dotGreenBlack.gif", QByteArray(), self)
At runtime, i want to change it by setting:
self.movie.setFileName("dotGreyStatic.gif")
But this leads to frame-freeze of the primarly set file "dotGreenBlack.gif"
Anything else i have to do to change the Gif-Animation on runtime?
Here is the fullcode:
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class ImagePlayer(QWidget):
def __init__(self, filename, title, parent=None):
QWidget.__init__(self, parent)
# Load the file into a QMovie
self.movie = QMovie(filename, QByteArray(), self)
size = self.movie.scaledSize()
self.setGeometry(200, 200, size.width(), size.height())
self.setWindowTitle(title)
self.movie_screen = QLabel()
# Make label fit the gif
self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.movie_screen.setAlignment(Qt.AlignCenter)
# Create the layout
main_layout = QVBoxLayout()
main_layout.addWidget(self.movie_screen)
self.setLayout(main_layout)
# Add the QMovie object to the label
self.movie.setCacheMode(QMovie.CacheAll)
self.movie.setSpeed(100)
self.movie_screen.setMovie(self.movie)
self.movie.start()
self.movie.loopCount()
self.movie.setFileName("dotGreyStatic.gif")
self.movie_screen.setMovie(self.movie)
if __name__ == "__main__":
gif = "dotGreenBlack.gif"
app = QApplication(sys.argv)
app.setStyleSheet("QWidget { background-color: black }")
player = ImagePlayer(gif, "was")
player.show()
sys.exit(app.exec_())
Gif Icons used in this Example:
You just need to stop and restart the movie:
self.movie.stop()
self.movie.setFileName("dotGreyStatic.gif")
self.movie.start()

Python code to change displayed image with pyqt4 on request

I have the following code to display am image using pyQt:
app = QtGui.QApplication(sys.argv)
window = QtGui.QMainWindow()
window.setGeometry(opts.posx, opts.posy, opts.width, opts.height)
pic = QtGui.QLabel(window)
pic.setGeometry(5, 5, opts.width-10, opts.height-10)
pixmap = QtGui.QPixmap(opts.filename)
pixmap = pixmap.scaledToHeight(opts.height)
pic.setPixmap(pixmap)
window.show()
sys.exit(app.exec_())
I would like to wrap up this code possibly in the form of a class, and be able to set a different image during runtime, using signals, socket, threads I really do not know. I would imagine something like:
class MyImage(object):
def __init(self, args):
some setup code
self.pic = whatever
def set_image(self, filename):
pixmap = QtGui.QPixmap(opts.filename)
pixmap = pixmap.scaledToHeight(opts.height)
pic.setPixmap(pixmap)
With the original code I just call sys.exit(app.exec_()) which makes the code 'freeze'. But I want to send a signal (and a filename) from a different running python code. Any suggestion how this can be handled easily and straightforward? Maybe overwriting the app.exec_ method?
Something like this should work for you:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4 import QtGui, QtCore
class ImageChanger(QtGui.QWidget):
def __init__(self, images, parent=None):
super(ImageChanger, self).__init__(parent)
self.comboBox = QtGui.QComboBox(self)
self.comboBox.addItems(images)
self.layout = QtGui.QVBoxLayout(self)
self.layout.addWidget(self.comboBox)
class MyWindow(QtGui.QWidget):
def __init__(self, images, parent=None):
super(MyWindow, self).__init__(parent)
self.label = QtGui.QLabel(self)
self.imageChanger = ImageChanger(images)
self.imageChanger.move(self.imageChanger.pos().y(), self.imageChanger.pos().x() + 100)
self.imageChanger.show()
self.imageChanger.comboBox.currentIndexChanged[str].connect(self.changeImage)
self.layout = QtGui.QVBoxLayout(self)
self.layout.addWidget(self.label)
#QtCore.pyqtSlot(str)
def changeImage(self, pathToImage):
pixmap = QtGui.QPixmap(pathToImage)
self.label.setPixmap(pixmap)
if __name__ == "__main__":
import sys
images = [ "/path/to/image/1",
"/path/to/image/2",
"/path/to/image/3",
]
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow(images)
main.show()
sys.exit(app.exec_())

Resources