Converting bytes to an image with base64 via PyQt5 - python-3.x

I've converted a png file like this with base64
b'iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAangAAGp4B8NQjJQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANRSURB\nVGiB7dpPqFVVFMfxz3tKVGS97EEGGYSZORGKJxHUw/4QgeNoVDTMAiuhoSAIgaD9/wMNhBo0qCZN\nghpIf0ZiDeRFFBJBEpFWgqG+euptsN957Hc853ruOeteL+IPFhzOvay1v/vss/beax+uaLw0Eezv\nGmzGpkWbKv1+AnM4jG9xJjh+J92CF/A15tFraPP4Cs9jzchbnelOfICzmje+zs7ifdwxSoDr8RoW\nAgDKtoB9WDVsiEfw2xAAynYUDw4LYhfOjQCisHPYGQkwgTdGCFC2VwVl13cvIURh73SFeGkMIAp7\nsS3EFjGp9TiexlrciifxRws/C3hgUIgbxGSnf3FPhf9N0qw+qL+jUvpvrDcDIHr4tE+MT1r6fKUp\nxAYxQ6onJYo6vd7S5wLWNQHZHwTRw/dYWRFjhbRwbOv3vYtBTEvjOgqkJ/V8DrMCezv6nMfqfiDb\ngyEKm8Nb0rvX5Unk9mw/kG+GBDIM+zJveD71r8Lfqsf0OOo/aXidYnmjN4uDOIID+FWak+7CY7gq\nyL9FXzPS5myZntPtUR+TcvzdNYE34OeOMcq2rSpQ27xe2DM1ALnuDQZZmhwnsyA3NWhIPz0hvWM9\n/ODCwgMcxO8d4+SaLi5ykOs6Ot2CGxevN0q9X6V/OsbJtbQlzkGiS0OnKu5N4ObAGEttzkEie+q8\nNLzKuk3KYlE6WVzkIH8FBpiT3peyZgNjwJ/FRQ7yU2CAz2rubw2MQdbmHOTHwACfV9ybxMOBMahp\n87UGK3nW2QnVK4T7AnzndgZXF87zJ3Iahxr2RD8dkDZmZT0a4DvXQanjsRwEPg4I8EXN/YcCfOf6\nqN+PERurmQq/k9ITjxpWF91Y0X2rO32hS9OBED0Ntrp0Lz5UlWtWSqvj4j/nta8jNy4+0K0cVJdi\n1+IpaXG5UftjicblILoV6A7rf74xJVX22/geuEBHt5LpL9KR2qw0DNbjcXyoXYWxGFIDl0wLXRZF\n7EIvjwHE7q4QpDX/vksIsUfwXmmH4RyA9nsntkcC5Jo1usPQ+4cFUeiyOJ7OtU46NmibTnM7jbdx\n+ygBypqSCsptP+HYprp0NJCG8VHNjFQiXS+tUIuZ+KRUFzgi7ey+M2Yf1VxRpP4H+dEoOtaum3IA\nAAAASUVORK5CYII=\n'
I have a GUİ to convert this code to and image again but when I enter it and take it with .toPlainText() it turns nothing.
It works if I manually type in the script:
How can I define a variable to fix that?

The problem is that toPlainTex() returns a string that in reality must be a bytearray, a way to convert it is using ast.literal() as I show below:
import ast
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
lay = QtWidgets.QVBoxLayout(self)
self.textEdit = QtWidgets.QTextEdit()
self.label = QtWidgets.QLabel()
self.label.setAlignment(QtCore.Qt.AlignCenter)
button = QtWidgets.QPushButton("convert")
lay.addWidget(self.textEdit)
lay.addWidget(button)
lay.addWidget(self.label)
button.clicked.connect(self.on_clicked)
def on_clicked(self):
text = self.textEdit.toPlainText()
try:
data = ast.literal_eval(text)
ba = QtCore.QByteArray.fromBase64(data)
pixmap = QtGui.QPixmap()
if pixmap.loadFromData(ba, "PNG"):
self.label.setPixmap(pixmap)
except SyntaxError:
pass
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

Related

How to translate ui file + several questions [duplicate]

I am trying to translate my small application written in pyside2/pyqt5 to several languages, for example, Chinese. After googling, I managed to change the main window to Chinese after select from the menu -> language -> Chinese. However, the pop up dialog from menu -> option still remains English version. It seems the translation info is not transferred to the dialog. How do I solve this?
Basically, I build two ui files in designer and convert to two python files:One mainui.py and one dialogui.py. I then convert the two python file into one *.ts file using
pylupdate5 -verbose mainui.py dialogui.py -ts zh_CN.ts
after that, in linguist input the translation words. I can see the items in the dialog, which means this information is not missing. Then I release the file as zh_CN.qm file. All this supporting file I attached below using google drive.
Supporting files for the question
The main file is as
import os
import sys
from PySide2 import QtCore, QtGui, QtWidgets
from mainui import Ui_MainWindow
from dialogui import Ui_Dialog
class OptionsDialog(QtWidgets.QDialog,Ui_Dialog):
def __init__(self,parent):
super().__init__(parent)
self.setupUi(self)
self.retranslateUi(self)
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.actionConfigure.triggered.connect(self.showdialog)
self.actionChinese.triggered.connect(self.change_lang)
def showdialog(self):
dlg = OptionsDialog(self)
dlg.exec_()
def change_lang(self):
trans = QtCore.QTranslator()
trans.load('zh_CN')
QtCore.QCoreApplication.instance().installTranslator(trans)
self.retranslateUi(self)
if __name__=='__main__':
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
ret = app.exec_()
sys.exit(ret)
I think it should be a typical task because almost no application will only have a mainwindow.
You have to overwrite the changeEvent() method and call retranslateUi() when the event is of type QEvent::LanguageChange, on the other hand the QTranslator object must be a member of the class but it will be deleted and it will not exist when the changeEvent() method is called.
Finally assuming that the Language menu is used to establish only translations, a possible option is to establish the name of the .qm as data of the QActions and to use the triggered method of the QMenu as I show below:
from PySide2 import QtCore, QtGui, QtWidgets
from mainui import Ui_MainWindow
from dialogui import Ui_Dialog
class OptionsDialog(QtWidgets.QDialog,Ui_Dialog):
def __init__(self,parent):
super().__init__(parent)
self.setupUi(self)
def changeEvent(self, event):
if event.type() == QtCore.QEvent.LanguageChange:
self.retranslateUi(self)
super(OptionsDialog, self).changeEvent(event)
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.m_translator = QtCore.QTranslator(self)
self.actionConfigure.triggered.connect(self.showdialog)
self.menuLanguage.triggered.connect(self.change_lang)
# set translation for each submenu
self.actionChinese.setData('zh_CN')
#QtCore.Slot()
def showdialog(self):
dlg = OptionsDialog(self)
dlg.exec_()
#QtCore.Slot(QtWidgets.QAction)
def change_lang(self, action):
QtCore.QCoreApplication.instance().removeTranslator(self.m_translator)
if self.m_translator.load(action.data()):
QtCore.QCoreApplication.instance().installTranslator(self.m_translator)
def changeEvent(self, event):
if event.type() == QtCore.QEvent.LanguageChange:
self.retranslateUi(self)
super(MainWindow, self).changeEvent(event)
if __name__=='__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
ret = app.exec_()
sys.exit(ret)

Reverting imported dictionary via QPushButton issues

I am having trouble understanding why a deep copy of a dictionary reverts back to original values when I run the revert() method once, but when I change values again, and run the revert() method again it changes the copied dictionaries values along with the original.
The dictionary/values are being imported from another file. I can only assume it is because the Test is being imported more than once.
Can someone help explain why this is happening and what can I do to avoid it?
Test.py
import ujson,copy
nested1 = {'1':None, '2':"String"}
nested2 = {'1':0.5123, '2':515}
diction = {'1':nested1, '2':nested2}
copyDiction = ujson.loads(ujson.dumps(diction))
copyOtherDiction = copy.deepcopy(diction)
Main.py
import Test
from PyQt5 import QtCore, QtWidgets, QtGui
class Window(QtWidgets.QMainWindow):
def __init__(self, parent = None):
super(Window,self).__init__(parent)
widget = QtWidgets.QWidget()
self.setCentralWidget(widget)
layout = QtWidgets.QVBoxLayout()
self.lineEdit = QtWidgets.QLineEdit()
self.button = QtWidgets.QPushButton("Change Value")
self.button.clicked.connect(self.changeMethod)
self.revertbutton = QtWidgets.QPushButton("Revert")
self.revertbutton.clicked.connect(self.revert)
layout.addWidget(self.lineEdit)
layout.addWidget(self.button)
layout.addWidget(self.revertbutton)
widget.setLayout(layout)
def changeMethod(self):
text = self.lineEdit.text()
if text.isdigit():
Test.diction['1']['2'] = int(text)
else:
Test.diction['1']['2'] = text
def revert(self):
print(Test.diction)
Test.diction = Test.copyDiction
print(Test.diction)
print(Test.copyDiction)
def main():
import sys
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

how to change cwd with lineEdit input in pyqt5

I want to change the cwd with a lineEdit input
basically type in the new path and changethe cwd with click on the button
# widgets
self.speicherort_input = qtw.QLineEdit()
self.speicherort_button = qtw.QPushButton("Speicherort_bestaetigen")
# signal
self.speicherort_button.clicked.connect(self.set_newpath)
# function
def set_newpath(self):
neuer_speicherort = self.speicherort_input.text()
os.system('cd' + neuer_speicherort) # how to change variable to raw string ?
how can I change the input string into a raw string to change the cwd ?
I changed the function to convert the lineEditt_input into a raw string
neuer_speicherort = self.speicherort_input.text()
raw_string = r"{}".format(neuer_speicherort)
os.chdir(raw_string)
but the command did not get executed
Tru it
import sys
import os
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg
class MainWindow(qtw.QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.resize(700, 410)
speicherort_label = qtw.QLabel("welcher Speicherort")
self.speicherort_input = qtw.QLineEdit()
self.speicherort_button = qtw.QPushButton("Speicherort_bestaetigen")
self.check_cwd_button = qtw.QPushButton("Check cwd")
layout1 = qtw.QFormLayout()
self.setLayout(layout1)
layout2 = qtw.QHBoxLayout()
layout2.addWidget(self.speicherort_input)
layout2.addWidget(self.speicherort_button)
layout1.addRow(speicherort_label, layout2)
layout1.addRow(self.check_cwd_button)
self.show()
# funktionen
self.speicherort_button.clicked.connect(self.changecwd)
self.check_cwd_button.clicked.connect(self.printcwd)
def changecwd(self):
neuer_speicherort = self.speicherort_input.text()
# raw_string = r"{}".format(neuer_speicherort)
# new_process = qtc.QProcess()
# new_process.setWorkingDirectory(raw_string)
os.chdir(neuer_speicherort) # +++
def printcwd(self):
print(os.getcwd())
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
w = MainWindow()
sys.exit(app.exec_())

Reading frames from a folder and display in QGraphicsView in pyqt4

I am trying to read frame for a folder and display in QGraphics view.
import os
import PyQt4
from PyQt4 import QtCore, QtGui
dir = "frames"
for file in os.listdir(dir):
grview = QtGui.QGraphicsView()
scene = QtGui.QGraphicsScene()
#pixmap = QtGui.QPixmap(os.path.join(dir, file))
pixmap = QtGui.QPixmap(file)
item = QtGui.QGraphicsPixmapItem(pixmap)
self.scene.addItem(item)
grview.setScene()
grview.show()
#self.scene.update()
The folder named "frames" contains jpg files and is in the same folder as the code. But still I am not able to read the frames.
I have also tried general display without graphicsview to check if it works using the code below but it too doesn't work.
import cv2
import os
import PyQt4
from PyQt4 import QtGui,QtCore
import matplotlib.pyplot as plt
from PIL import Image
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
img = cv2.imread(os.path.join(folder,filename))
if img is not None:
images.append(img)
return images
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
img = load_images_from_folder('/frames')
image = Image.open(img)
image.show()
I am not able to understand what am I missing. I want to display the images sequentially in QGraphicsView resembling a video and in some particular frame I have to select the object of interest by draw a rectangle around it which has to hold in the subsequent frames as well. Is the task i am attempting possible? if yes any help is appreciated
Sorry, but I have PyQt5.
Try it:
import os
import sys
from PyQt5 import Qt
#from PyQt4 import QtCore, QtGui
class MainWindow(Qt.QMainWindow):
def __init__(self, parent=None):
Qt.QMainWindow.__init__(self, parent)
self.scene = Qt.QGraphicsScene()
self.grview = Qt.QGraphicsView(self.scene)
self.setCentralWidget(self.grview)
dir = "frames"
self.listFiles = os.listdir(dir)
self.timer = Qt.QTimer(self)
self.n = 0
self.timer.timeout.connect(self.on_timeout)
self.timer.start(1000)
self.setGeometry(700, 150, 300, 300)
self.show()
def on_timeout(self):
if self.n < len(self.listFiles):
self.scene.clear()
file = self.listFiles[self.n]
pixmap = Qt.QPixmap("frames\{}".format(file)) # !!! "frames\{}"
item = Qt.QGraphicsPixmapItem(pixmap)
self.scene.addItem(item)
self.grview.setScene(self.scene) # !!! (self.scene)
self.n += 1
else:
self.timer.stop()
app = Qt.QApplication(sys.argv)
GUI = MainWindow()
sys.exit(app.exec_())

populating combo box with folders on disk using QFileSystemModel

Hi I have written this basic code trying to populate folders underneath the /Users/ directory, but I don't know what I am missing its not populating.
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class MyWindow(QtGui.QWidget):
"""docstring for MyWindow"""
def __init__(self, parent=None):
super(MyWindow, self).__init__()
self.setup()
def setup(self):
fsm = QtGui.QFileSystemModel()
fsm.setRootPath("/Users/")
layout = QtGui.QVBoxLayout()
combo = QtGui.QComboBox()
combo.setModel(fsm)
layout.addWidget(combo)
self.setLayout(layout)
def main():
app = QtGui.QApplication(sys.argv)
win = MyWindow()
win.show()
win.raise_()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I am getting a / in the comobobox instead of the whole list of folders under /Users/ directory.
I think its better to use QFileSystemModel instead of using os.listdir interms of efficiency and will update the view if somebody updates folder or adds folder in the /Users/ directory !
Remember that QFileSystemModel is a hierarchical model, so you need to let the QComboBox know which QModelIndex represents the children you want to display. You do that with QComboBox.setRootModelIndex()
QFileSystemModel.setRootPath() conveniently returns the QModelIndex of the path you set.
So a small change is all you need (tested on Windows) -
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class MyWindow(QtGui.QWidget):
"""docstring for MyWindow"""
def __init__(self, parent=None):
super(MyWindow, self).__init__()
self.setup()
def setup(self):
fsm = QtGui.QFileSystemModel()
index = fsm.setRootPath("/Users/")
layout = QtGui.QVBoxLayout()
combo = QtGui.QComboBox()
combo.setModel(fsm)
combo.setRootModelIndex(index)
layout.addWidget(combo)
self.setLayout(layout)
def main():
app = QtGui.QApplication(sys.argv)
win = MyWindow()
win.show()
win.raise_()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

Resources