I'm running into a bit of a problem and could use some help.
I have here a small pyqt app that displays a pixmap.
import sys
import qtcompress
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def window():
str_image = 'AAASDHicnVdlUBSO076DOySlUzqkuxuU7pRG8hAE6QY5uhvkaCXlSEGk4TyPUvBoCQlJT+CkO/7+Pr/f3mfm2Zjd2f2wszuzyUYGmiSEDIQAAIBEW0vN5J9W+Y/4eP8k3N135Z8C+T/RNsP/hwh8l6R/PoGPlpU/AEBE+R+BgKISun85D9zNLAMs9fXknL29hBxdvJ1chUK8fABAgLmZhqAM4P9GXkTvF4+/qtegGj4PJUQtfzRxvGj5zKoX8LL2HPJLSsdk2UW2jN6TyoFnbX60PnBS8w9/AN5NNEmGwGmQKZOLzaHszv296JfCQ08KW28/PXvL6rEF9u9Df1aj7qr5RJnqVxPEnd8YzovdXdm3JJ4/Zxm9Jjp8H8ZkD34UlbvNW9/Sqp3bcCLtTG2q5NZ/YZOQDZ/hmv1meStA+XV6z6DwIIb36fJkkrtNyi5me6JNI7ac6psIkwtxFsa9Zj/1B8LoUwGDfTL67dvsKOVb11TK1aE/rXA/lnenYY3NXqW0RGznCi6WI60Sxu/yva3ipa2fvfbQC1IyfZbD/r0e5pZyk7ETYZ5ufqrjbrfkW33JnJcfpqhRekDl5ZOht6zipta2MNwqsW/+Znb85emH1oiIb/TdblzPqeOWe1sbrmbc1EdXuJ9Taysq57G+aTHT0vnlerbypH+TWrjgZqzzHNNW2bzO8+fH1zEr+iWUm4vY9AgyVogsd8+QMIHfXsGvLE6/YHn/lWGhnosFyem7oy8dMpURdnd0b02Ny1mKU4J5PjZBiCWmQyWIF7KfGorbropYP9bfSh7WC1AepO5Hbb0/m0mclgnrGdkyCt0TLb7ssLL6lday5M6DE8Zouhpgt945Nue5rrHIw0A2zhHwduENZSGHswoHBzw9c4tpl5ebf0GH/YdA5NfkllXpJO+2kbJMAZs2AYufvaO2JKT68PSGrmTFR8Uum3sqgm0Pf3ew08hTGlhL+gmYITT8Y4v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sTeMmwmmBb2VFOFpz+uK9YHt/mwdgus82ATxThARNVRtZn+Jw8pmhvqq607ZTavJMOE0jOfQeZMJmfidrKQpOeNAhxdaXR0NBgCzIARQBk8PZo3JG653UbIwsPs2oGZuyze9vV/Icosou4QnsI7LCFhA0RNb0N9PGrDBEsMmwXg80RW/U/JG+rAYD5+fmk/Nn8DlBZ8VTP+TDiWVpdYJXY08caryLomBzzZ+oSNFg+vJgIWWHhVDMI3TkTwemk/DzE2qvi82StsbYszGMJKQwGIIauhj52d7eCj+zWghGViF9Xm4zXJm1yi8+YPTa6v1M7f8MBt2KCGQYEZD0SuZHhk4oGFF8GmyNvd6U5FX6iNEZPT9Mt7az6tBazThIQtNzrqrzy6vXw9jnSU8uswT43Mm/W/CInznZkIgPuHfRAfC0csYuQX73ZXl1tOfDJtXH9IT2He3G7uLgYBbiv99HJqlRj1M53ZrCQEqJqPV780G1bv4XvcHDEIBc/0euMNWMVJh3JFPlUFrpdWLzIH/EtKLW5sTEZjjVpN5eMnOfcp/nx+kHICqPiKqg0OJ3U3T9gUc3Ly6aPT4oulqTW/JRaXN4dsgsJwiy4lfdhBlePVokYFUKMZmb0vDLhSm89zotHuc291HeDLvFiMFAaVS/YPQSRcBIOnP0RQGcv2S74aMYw4h7136vw4K0ytu/c3nj2LJW8PbMYswzvhkPC9feDxJerb4U1xub0T9OKbv2MruNJPrnC74SVLz73tE4EU0PvSYfD7zRN/+K2TBPNYzYiAUFhQPnIG5axlCmO0mvWRsA/aKsbqDU9cYj5Hz3VwP4='
app = QApplication(sys.argv)
win = QWidget()
l1 = QLabel()
image = qtcompress.decode_thumbnail(str_image)
l1.setPixmap(QPixmap.fromImage(image))
vbox = QVBoxLayout()
vbox.addWidget(l1)
win.setLayout(vbox)
win.setWindowTitle("QPixmap Demo")
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
Here is the decode_thumbnail function
def decode_thumbnail(str_image):
bytearray = QtCore.QByteArray.fromBase64(str_image)
bytearray = QtCore.qUncompress(bytearray)
image = QtGui.QImage()
image.fromData(bytearray, 'PNG')
I've looked around a lot and can't seem to find any examples of anyone unpacking a string from base64 and then using qUncompress. Python is not my forte in any way, so I apologize if this is a simple question.
The problem is in your decode_thumbnail function. It isn't returning anything.
Change the last line from
image.fromData(bytearray, 'PNG')
to
return image.fromData(bytearray, 'PNG')
Alternatively, as QImage.fromData is a static method, you don't need an image object, so you can just write
def decode_thumbnail(str_image):
bytearray = QByteArray.fromBase64(str_image)
bytearray = qUncompress(bytearray)
return QImage.fromData(bytearray, 'PNG')
Related
I made a QGraphicsTextItem and set plain text as its content. After that, I set the QGraphicsTextItem inside the QGraphicsWidget.
My question is, Is it possible to resize the QGraphicsTextItem including its text/contents like in this picture:
This is the video of the resizing that I'm asking for.
If this is possible, how can I apply it to the QGraphicsTextItem?
The first picture is the image of the QGraphicsTextItem but I have no idea how to implement the resizing in the video.
Things I've tried:
I tried using the setTextWidth() and setting it to 0.5 but it's not working.
I also tried using adjustSize() to the QGraphicsTextItem but it's also not working.
Code to reproduce the issue:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.view = QGraphicsView()
scene = QGraphicsScene()
#before resizing
item = QGraphicsTextItem("Line 1 Line 2 Line 3")
item.setFlags(QGraphicsWidget.ItemIsSelectable)
item.setPos(self.view.mapToScene(2, 2))
scene.addItem(item)
#after resizing
item_1 = QGraphicsTextItem("Line 1\nLine 2\nLine 3")
item_1.setFlags(QGraphicsWidget.ItemIsSelectable)
item_1.setPos(self.view.mapToScene(2, 30))
scene.addItem(item_1)
self.view.setScene(scene)
self.setCentralWidget(self.view)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()
I have a Pyqt5 form where the user enters data. This data is sent to another module, where it is processed and returned for display in the form.
Very simplistically it looks like this:
frm.py
import sys
from PyQt5.QtWidgets import *
import mdl
def fnc0(in_val):
mdl.fnc1(in_val)
def fnc2(rezult):
msg.setText(rezult)
app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout()
btn = QPushButton('button')
btn.clicked.connect(lambda: fnc0(5))
layout.addWidget(btn)
msg = QLabel('')
layout.addWidget(msg)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
mdl.py
import frm
def fnc1(in_val):
out_val = str(in_val*2)
frm.fnc2(out_val)
However, when doing this, I get the error of using circular modules:
AttributeError: partially initialized module 'mdl' has no attribute 'fnc1' (most likely due to a circular import)
Is it possible to process the data sent from the form to another module, and then return the result to the form?
A possible solution is that in a third file we create a logic where we can register functions that receive the result and a function that invokes those functions:
core.py
_funct = []
def register_writer(func):
_funct.append(func)
return func
def write(text):
for f in _funct:
f(text)
mdl.py
import core
def fnc1(in_val):
out_val = str(in_val * 2)
core.write(out_val)
frm.py
import sys
from PyQt5.QtWidgets import *
import core
import mdl
#core.register_writer
def fnc2(rezult):
msg.setText(rezult)
app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout()
btn = QPushButton("button")
btn.clicked.connect(lambda: mdl.fnc1(5))
layout.addWidget(btn)
msg = QLabel()
layout.addWidget(msg)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
I'm using pyqtgraph and trying to recover the properties for my TextItem class objects added to a given graph.
Although it looks like it's a simple task, I can't figure out how to extract this and the documentation didn't help much.
Here's a snippet:
import sys
from PyQt5.QtWidgets import QApplication, QWidget
import pyqtgraph as pg
import numpy as np
def refreshScreen(AnnotationsList):
for i in range(len(AnnotationsList)):
c = AnnotationsList[i]
# Now I need to extract information from the annotations:
x = c.x()
print(x)
y = c.y()
print(y)
text = c.text()
print(text)
OtherProperties = c.getProperty()
print(OtherProperties)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QWidget()
w.resize(250, 150)
w.move(300, 300)
w.setWindowTitle('Simple')
w.show()
AnnotationsList = []
c = pg.TextItem(anchor=(0,0), border=pg.mkPen(200, 200, 200))
c.setText(text='my_annotation', color=(0,0,0))
# coordinates for annotation
x = 5
y = 10
c.setPos(x,y)
AnnotationsList = np.append(AnnotationsList, c)
refreshScreen(AnnotationsList)
sys.exit(app.exec_())
I guessed the .x() and .y() and got them right, but knowing how to extract other features would also be important! In the current form, it raises:
AttributeError: 'TextItem' object has no attribute 'text'
If you check the source code you see that TextItem has a QGraphicsTextItem that stores the information, so if you want to get the text information you should use that object:
text = c.textItem.toPlainText()
print(text)
I am trying to display a loading gif while other code executes. I am very unfamiliar with PyQt and have tried following the code at this link, which seems to be the standard way of executing a gif. I only want the gif playing and do not want a button. Here is the code I am currently at, but it is very poor.
self.movie = QMovie(coffeeloading.gif, self)
size = self.movie.scaledSize()
self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.movie_screen.setAlignment(Qt.AlignCenter)
self.movie_screen = QLabel()
main_layout = QVBoxLayout()
main_layout.addWidget(self.movie_screen)
self.setLayout(main_layout)
self.movie.setCacheMode(QMovie.CacheAll)
self.movie.setSpeed(100)
self.movie_screen.setMovie(self.movie)
self.movie.start()
This is supposed to execute after a button press and fill up the whole screen of 240x320, but I dont have any idea how to do it. I have already read through many of the other stackoverflow and other links, but none of them seem to address how to complete this.
As an alternative, you can use this class here.
QtWaitingSpinner extends the QtWidgets.QWidget class and you can start your spinner by simply running
your_QtWaitingSpinnerObject.start()
You can check this answer as well.
# -*- coding: utf-8 -*-
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class test_widget(QWidget):
m_play_state = False
def __init__(self):
super(test_widget, self).__init__()
self.__ui__()
def __ui__(self):
t_lay_parent = QVBoxLayout()
self.m_label_gif = QLabel()
self.m_button_play = QPushButton("Play")
t_lay_parent.addWidget(self.m_label_gif)
t_lay_parent.addWidget(self.m_button_play)
self.m_movie_gif = QMovie("loding.gif")
self.m_label_gif.setMovie(self.m_movie_gif)
self.m_label_gif.setScaledContents(True)
self.m_label_gif.hide()
self.setLayout(t_lay_parent)
self.m_button_play.clicked.connect(self.slt_play)
def slt_play(self):
if self.m_play_state:
self.m_label_gif.hide()
self.m_movie_gif.stop()
self.m_play_state = False
else:
self.m_label_gif.show()
self.m_movie_gif.start()
self.m_play_state = True
if __name__ == "__main__":
app = QApplication(sys.argv)
win = test_widget()
win.show()
sys.exit(app.exec_())
I'm still quite a newbie with Python and PyQt so I have a really basic question. I have some text and images in a parent window inside a QTextEdit widget and I'm trying to copy all the content to a child window's QTextEdit. But for some reason I can't get it to copy the image - only the text is copied not the image. Here's a snippet of the code that's giving me trouble:
self.textEdit.selectAll()
data = self.textEdit.createMimeDataFromSelection()
self.child_window.textEdit.insertFromMimeData(data) # doesn't work with images
Here's is the small program that I'm trying to run:
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyWindow(QtGui.QWidget):
def __init__(self,parent=None):
super(MyWindow,self).__init__(parent)
self.textEdit = QtGui.QTextEdit(self)
self.textEdit.setText("Hello World\n")
self.pushButton = QtGui.QPushButton(self)
self.pushButton.setText("Copy and paste to Child Window")
self.pushButton.clicked.connect(self.click_copy_data)
self.pushButton2 = QtGui.QPushButton(self)
self.pushButton2.setText("Insert Image")
self.pushButton2.clicked.connect(self.click_file_dialog)
self.layoutVertical = QtGui.QVBoxLayout(self)
self.layoutVertical.addWidget(self.textEdit)
self.layoutVertical.addWidget(self.pushButton2)
self.layoutVertical.addWidget(self.pushButton)
self.setGeometry(150, 150,640, 480)
self.child_window = CustomWindow(self)
self.child_window.show()
def click_copy_data(self):
self.textEdit.selectAll()
data = self.textEdit.createMimeDataFromSelection()
self.child_window.textEdit.insertFromMimeData(data)
def click_file_dialog(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.textEdit.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.textEdit.textCursor()
textCursor.movePosition(
QtGui.QTextCursor.End,
QtGui.QTextCursor.MoveAnchor
)
textCursor.insertImage(imageFormat)
# This will hide the cursor
blankCursor = QtGui.QCursor(QtCore.Qt.BlankCursor)
self.textEdit.setCursor(blankCursor)
class CustomWindow(QtGui.QDialog):
def __init__(self,parent=None):
super(CustomWindow,self).__init__(parent)
self.textEdit = QtGui.QTextEdit(self)
self.layoutVertical = QtGui.QVBoxLayout(self)
self.layoutVertical.addWidget(self.textEdit)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())
The way the program works is that you have some text inside the main window and then you insert an image. Then you click "Copy and paste to Child Window" button and it should paste all the contents to the child, including the image - but that doesn't work that way it's supposed to - the text is copied but I get a little file icon where the image should be.
I would appreciate your help on this.
Paul
QTextEdit doesn't decode image MIME types by default, so just subclass it to add support, you'll need to reimplement canInsertFromMimeData and insertFromMimeData, also try QTextBrowser instead. Just add this to your script:
class MyTextBrowser(QtGui.QTextBrowser):
def __init__(self, parent=None):
super(MyTextBrowser, self).__init__(parent)
self.setReadOnly(False)
def canInsertFromMimeData(self, source):
if source.hasImage():
return True
else:
return super(MyTextBrowser, self).canInsertFromMimeData(source)
def insertFromMimeData(self, source):
if source.hasImage():
image = QtCore.QVariant(source.imageData())
document = self.document()
document.addResource(
QtGui.QTextDocument.ImageResource,
QtCore.QUrl("image"),
image
)
cursor = self.textCursor()
cursor.insertImage("image")
super(MyTextBrowser, self).insertFromMimeData(source)
And change self.textEdit = QtGui.QTextEdit(self) into self.textEdit = MyTextBrowser(self) on both widgets.
This is the solution I ended using as suggested by X.Jacobs.
html = parent_textEdit.toHtml()
child_textEdit.setHtml(html)
I was making things more complicated. When I realized that QTextEdit keeps track of where the image is stored as a url inside the html generated by toHtml() then it all made sense.