How to get an image off the internet for QPixmap [duplicate] - python

This question already has answers here:
PyQt4 and Python 3 - Display an image from URL
(1 answer)
Display Image from URL
(3 answers)
Closed 29 days ago.
def window():
app = QApplication(sys.argv)
w = QWidget()
qlabel = QLabel(w)
qlabel.setPixmap(QPixmap("https://bipbap.ru/wp-content/uploads/2017/04/0_7c779_5df17311_orig.jpg"))
w.setWindowTitle("PyQt5 Image Viewer")
w.setGeometry(100,100,300,500)
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
window()
qlabel.setPixmap(QPixmap("https://bipbap.ru/wp-content/uploads/2017/04/0_7c779_5df17311_orig.jpg")) does not work.
qlabel.setPixmap(QPixmap("local.jpg")) works.
Why?
how use Qt.QNetworkAccessManager() for an array of pictures

Related

How to make standard threading run a function and populate a widget in Python/PyQt5 [duplicate]

This question already has answers here:
Qt - updating main window with second thread
(3 answers)
How do I create a Window in different QT threads?
(4 answers)
Closed 1 year ago.
I am trying to messing up with something and I am not able to create a widget using threading.
Could someone take a look at my test script and let me know why this does not work?
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import *
import threading
import time
class Main(QMainWindow):
def __init__(self):
super(Main, self).__init__()
self._build_ui()
main_thread = threading.Thread(target=self.thread_function)
main_thread.start()
def thread_function(self):
i = 0
while True:
message = "Message number: {}".format(i)
print (message)
self.create_message_widget(message)
i+=1
time.sleep(1)
def create_message_widget(self, message):
print ("Testing 3")
self.label = QLabel(self)
self.label.setText(message)
self.verticalLayout.addWidget(self.label)
def _build_ui(self):
self.setWindowTitle("Testing Window")
# set the central widget and main layout
self.centralWidget = QWidget(self)
self.verticalLayout = QVBoxLayout(self)
self.setCentralWidget(self.centralWidget)
self.centralWidget.setLayout(self.verticalLayout)
self.button = QPushButton("Run")
self.button.clicked.connect(lambda: self.create_message_widget("Testing 1"))
# adding widgets to the window
self.verticalLayout.addWidget(self.button)
self.create_message_widget("Testing 2")
self.create_message_widget("Testing 2")
self.create_message_widget("Testing 2")
# show main window
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Main()
sys.exit(app.exec())
The following script shows 3 functions where I did few Testing X.
You can notice the Testing 2 are created fine.
When we click the button we can see Testing 1 which is populated by button press.
In thread_function I call create_message_widget function and I thought that should automatically create widget every 1 sec but it does not do anything. Could someone explain why and if this is possible to make it works?

conect multiple buttons to same function with different parameters [duplicate]

This question already has answers here:
Lambda in a loop [duplicate]
(4 answers)
Connecting slots and signals in PyQt4 in a loop
(3 answers)
Using lambda expression to connect slots in pyqt
(4 answers)
Closed 3 years ago.
I want to create multiple buttons by a for loop.
Pressing on the buttons call same function but transfer a different parameters.
def someFunction(self):
buttons = [None] * 8
for i in range(8):
buttons[i] = QPushButton(self)
buttons[i].clicked.connect(self.function(i))
def function(self, i):
print(i)
I expect the output of buttons[i] to be i but the output always 7
Try it:
from PyQt5.QtWidgets import *
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout(self)
self.someFunction()
def someFunction(self):
# buttons = [None] * 8
for i in range(8):
button = QPushButton("Button {}".format(i), self)
button.clicked.connect(lambda ch, i=i: self.function(i)) # < ---
self.layout.addWidget(button)
def function(self, i):
print(i)
if __name__ == '__main__':
app = QApplication([])
mainapp = MainWindow()
mainapp.show()
app.exec_()

How to center text in a QLineEdit? [duplicate]

This question already has answers here:
Center the Text of QTextEdit horizontally and vertically
(2 answers)
Closed 3 years ago.
I searched about but can't find a solution to align in center the text inside the QLineEdit
Example:
https://i.imgur.com/XmmxqSf.png
alignment : Qt::Alignment
This property holds the alignment of the line edit
Both horizontal and vertical alignment is allowed here, Qt::AlignJustify will map to >Qt::AlignLeft.
By default, this property contains a combination of Qt::AlignLeft and Qt::AlignVCenter.
from PyQt5 import QtWidgets, QtCore
class Widget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.line_edit = QtWidgets.QLineEdit()
self.line_edit.setAlignment(QtCore.Qt.AlignCenter) # <-----
self.line_edit.textChanged.connect(self.on_text_changed)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.line_edit)
self.setLayout(layout)
def on_text_changed(self, text):
width = self.line_edit.fontMetrics().width(text)
self.line_edit.setMinimumWidth(width)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
mw = Widget()
mw.show()
app.exec()

Python Decode Base64 qUncompress Image

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/lWGhnosFyem7oy8dMpURdnd0b02Ny1mKU4J5PjZBiCWmQyWIF7KfGorbropYP9bfSh7WC1A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LJO9wNHXclz6H7Egj2tybnC3tJlwQLCX3o2YtPLhK1ih3OpHdkT/gT7ChdubsiTXg7pHMQ08m+aC9osVVKQDADV36iPRfHS5KYQMkEz7/+uA3/xFe7MSt16lyXUXbTeQ7OrIcojy2U496n6xJv9V3SxZT7asH8y0ttNGmhgqHqE9BmcsTeMmwmmBb2VFOFpz+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')

PyQt: Why does new window close immediately after opening it [duplicate]

This question already has answers here:
PyQt window closes immediately after opening
(3 answers)
Closed 12 months ago.
I have a main window and I want to open a another window (not a dialog) on button press. My problem is that the new window closes almost immediately after it opens. I have read the available articles, and tried to implement the solutions, but seem to have no luck. This is my entire code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MainWindow (QMainWindow):
def __init__(self):
win = QWidget()
win.adjustSize()
grid=QGridLayout()
grid.setRowStretch(0, 1)
grid.setRowStretch(1, 1)
grid.setRowStretch(5, 1)
for i in range(0,5):
for j in range(0,4):
if i==0 and j==2:
l1=grid.addWidget(QLabel("Choose an option:"),i,j, 2, 2)
if i==2 and j==1:
b1= QPushButton("Get Best Match")
grid.addWidget(b1,i,j)
elif i==2 and j==2:
b2=QPushButton("Button2")
grid.addWidget(b2,i,j)
elif i==2 and j==3:
b3=QPushButton("Button3")
grid.addWidget(b3,i,j)
b5=grid.addWidget(QLabel(""),3,4)
b4=QPushButton("Button4")
grid.addWidget(b4,2,4)
w1=b1.clicked.connect(window1)
b2.clicked.connect(Win2)
b3.clicked.connect(Win3)
b4.clicked.connect(Win4)
win.setLayout(grid)
win.setGeometry(100,100,width//2,height//2,)
win.setWindowTitle("PYQT")
win.show()
win.setStyleSheet("""
.QPushButton {
height: 30px ;
width: 20px ;
}
.QLabel {
qproperty-alignment: AlignCenter;
font-size:12pt
}
""")
sys.exit(app.exec_())
class window1():
def __init__(self, pressed):
super(window1, self).__init__()
win1 = QWidget()
win1.adjustSize()
win1.setGeometry(100,100,width//2,height//2,)
win1.setWindowTitle("Get Best Match")
win1.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
screen_resolution = app.desktop().screenGeometry()
width, height = screen_resolution.width(), screen_resolution.height()
main=MainWindow()
Could someone please help me with this? I have been stuck for some time now.
The window is disappearing because it goes out of scope at the end of your __init__ function. Since there are no further references to it, the python garbage collector removes it.
Usually PyQt objects keep references to their children so this is not a problem. Since you want the widget to open in a separate window, you can't assign it a parent, so you need to store a reference to it somewhere else. The obvious candidate is the MainWindow class.
You can make win a member of MainWindow by using self.win = QWidget() instead of win = QWidget(). The window will now stay open for the lifetime of MainWindow unless you close it.
You have other problems with your code, but this explains why the window disappears.

Categories