Display an image when pressing a button in Qt GUI (Python) - python

I drew a GUI in Qt Creator, with a button, a slider and some labels.
What I am trying: when the button is pressed, print on terminal and in a label the modified value of the slider and display an image. As many webpages suggested, I am trying to display an image into a label by using the pixmap method. This is my whole code (the structure of the GUI is in the imported mainwindow.ui file)
import sys
from PyQt4 import QtCore, QtGui, uic
qtCreatorFile = "mainwindow.ui"
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class myownGUI(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
#button
self.Do_button.clicked.connect(self.action)
#slider
self.SLIDER.valueChanged[int].connect(self.SLIDER_update)
#"global" variable init. by callback
self.SLIDER_update()
#The button callback
def action(self):
print "DOING ACTION!"
print self.Slider
#trying to display the image in the Image_label
image = QtGui.QImage(QtGui.QImageReader(":/images/test.png").read())
self.Image_label.setPixmap(QtGui.QPixmap(image))
#self.Image_label.show() #unuseful command?
#Slider update callback
def SLIDER_update(self):
self.Slider= self.SLIDER.value()
if (self.Slider % 2 == 0): #even
self.Slider = self.Slider + 1
self.Slider_label.setText(str(self.Slider))
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = myownGUI()
window.show()
sys.exit(app.exec_())
The code runs, it shows no error but the image is not displayed.
I tried both JPG and PNG images. I tried also the simple image name, when the image is in the same folder.
What is wrong in my code?
There is another way to display images in QT inside the GUI (with python) ?
Thank you in advance
Working with: Ubuntu 14.04 / Qt version 4.8.6
I try to read all similar questions in stack overflow. It seems that my question is duplicated, but none of the answers seems to resolve my problem.
EDIT: Using PRMoureu's syntax it works also when the image is the same folder, like
image = QtGui.QImage(QtGui.QImageReader("./test.png").read())
Now the image is displayed and have only to be rescaled.

You should call the image with another path syntax :
image = QtGui.QImage(QtGui.QImageReader("./images/test.png").read())
or
image = QtGui.QImage(QtGui.QImageReader("images/test.png").read())

Related

How to run one function only after another, at pushbutton using PYQT

I've read multiple posts on this and couldn't fix my code.
I'm running a GUI (using PyQt5) that runs a function (Extraction()) from another script (file_py). What I want to do is the script to display a Green Led picture (.png) at start, and then when pushbutton is clicked, before running Extraction(), the GUI would display a Red Led picture.
from PyQt5 import QtCore, QtGui, QtWidgets
import file_py as my_script
def setupUi(self, MainWindow):
self.pushButton.clicked.connect(self.trigger_status_icon)
self.LED_Green = QtGui.QPixmap("C:/Desktop/green-led-on.png")
self.LED_Red = QtGui.QPixmap("C:/Desktop/red-led-on.png")
self.labelStatus = QtWidgets.QLabel()
self.labelStatus.setPixmap(self.LED_Green) #starting GUI with a Green Led picture
self.labelStatus.setScaledContents(True)
def trigger_status_icon(self):
self.labelStatus.setPixmap(self.LED_Red)
return self.run_Script()
def run_Script(self):
my_script.Extraction()
But what I'm getting with this code is the following: At the start of the GUI a Green Led picture is displayed. After pushbutton is clicked the function Extraction() runs, and only after it finishes the Led Red picture appears.
What can I do so that the Led Red picture is run before the function Extraction()?
By adding QtWidgets.QApplication.processEvents() after assigning the picture it will refresh the QtWidget.
def trigger_status_icon(self):
self.labelStatus.setPixmap(self.LED_Red)
QtWidgets.QApplication.processEvents()
return self.run_Script()
When you have a change in UI followed by some "lengthy" operation you can explicitly refresh the UI by using the QWidget.update method:
def trigger_status_icon(self):
self.labelStatus.setPixmap(self.LED_Red)
self.update()
return self.run_Script()

How to add Video Player inside the Qwidget? [duplicate]

This question already has answers here:
How to add a QVideoWidget in Qt Designer?
(3 answers)
Closed 1 year ago.
I want to add a Video player inside this box.
Screen shot of the UI:
I have designed the UI in Qt Designer and this box is a Qwidget named "video". I don't know how to integrate the Video player inside of this box. I am aiming to upload the fetch the file directory from the button "Upload Video" and then play the video from the directory in the Video Player that will be in the box. I would appreciate the help.
Here is the GUI code for the widget that has been inserted.
self.video = QWidget(self.Home_page)
self.video.setObjectName(u"video")
self.video.setStyleSheet(u"border:1px solid white\n""")
self.verticalLayout_6.addWidget(self.video)
You can use a QFileDialog to let the user choose the file he wants. It will provide you the filesystem path to the file. Then, you can use a QMediaPlayer to load the file using its path.
Edit : Example (I used PySide but it should work if you replace with PyQt) :
from PySide2 import QtCore, QtWidgets, QtMultimedia, QtMultimediaWidgets
class VerySimpleMediaPlayer(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__(parent)
self.open_file_button = QtWidgets.QPushButton("Open file")
self.open_file_button.clicked.connect(self.open_file)
self.media_player = QtMultimedia.QMediaPlayer(self)
self.media_widget = QtMultimediaWidgets.QVideoWidget(self)
self.media_player.setVideoOutput(self.media_widget)
self.media_widget.show()
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.open_file_button)
layout.addWidget(self.media_widget)
self.setLayout(layout)
def open_file(self):
filepath, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Choose video file to load")
self.media_player.setMedia(QtCore.QUrl.fromLocalFile(filepath))
self.media_player.setVolume(20) # not too loud
self.media_player.play()
if __name__ == "__main__":
app = QtWidgets.QApplication([])
main_window = QtWidgets.QMainWindow()
example_widget = VerySimpleMediaPlayer(main_window)
main_window.setCentralWidget(example_widget)
main_window.setVisible(True)
app.exec_()
It worked for listening to a MP3 file, but did not work for a MP4 file, maybe because of codecs. Try it yourself.
I used these docs :
QtWidgets.QFileDialog (PySide)
QtMultimedia.QMediaPlayer (Qt)
QtMultimediaWidgets.QVideoWidget (Qt)

Can't set transparency of QWindow after shown once while opaque

I have a window I'm trying to make transparent after being shown once while opaque. However, doesn't go transparent even if I hide and show again. This is what I get:
But I want it like this: (transparent against background)
If I run WA_TranslucentBackground first, before .show() it creates a nice transparent button as expected.
Here is an example code which shows a floating button when you run it
import sys
from PySide2 import QtCore, QtWidgets, QtGui
class TransparentWindow(QtWidgets.QMainWindow):
def __init__(self):
super(TransparentWindow, self).__init__()
self.setCentralWidget(QtWidgets.QWidget(self))
self.mainLayout = QtWidgets.QVBoxLayout()
self.centralWidget().setLayout(self.mainLayout)
self.mainLayout.addWidget(QtWidgets.QPushButton("Hello World", parent=self))
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
self.show() # If I move this under '.setAttribute()' it works
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
demo = TransparentWindow()
sys.exit(app.exec_())
I've tried hiding and reshowing, 'setAutoFillBackground()' and 'WA_NoSystemBackground' attribute, but I cant seem to get it to work. Anybody have any idea how to set the transparency after it has been shown as opaque?
Using versions QtCore: 5.9.6, Pyside2: 5.9.0a1.dev1528389443

PyQt resize QMovie with proper anti-aliasing

I created a QLabel and set it's movie to a QMovie object with an animated gif. Then in the resizeEvent of my app I resize and move the label, so that it is centered/fit to the layout. This works fine but the movie has a lot of fine lines which get totally garbled in the resize operation, it seems there is no anti-aliasing. So either I am using the wrong resize method, or I need to set anti-aliasing somewhere right? There is nothing in the QMovie or QLabel documentation to suggest how to do this. I did read that the QMovie is inherited from a QImageReader, though that too has no property for anti-aliasing that I could find.
EDIT
I did somewhat get this to work, but it's still not quite right. I found that QMovie has a setScaledSize method which actually scales the underlying QImageViewer. Then I just have the label adjust to it's contents, namely the movie. Using the following code I am able to resize the movie with proper anti-aliasing, however it is quite "jumpy" and "flickery" during resize so obviously I'm not doing this quite "right". Also it somehow loses it's aspect ratio sometimes. Still looking for the correct way to do this... Maybe a QLabel is the wrong way to go?
Here's a working example
import sys
from PyQt4 import QtGui
class MovieTest(QtGui.QDialog):
def __init__(self):
super(MovieTest, self).__init__()
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
self.loading_lbl = QtGui.QLabel()
self.loading_lbl.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicyIgnored)
self.loading_lbl.setScaledContents(True)
layout.addWidget(self.loading_lbl)
loading_movie = QtGui.QMovie("loading-radial_loop.gif") # some gif in here
self.loading_lbl.setMovie(loading_movie)
loading_movie.start()
self.setGeometry(50,50,100,100)
self.setMinimumSize(10,10)
def resizeEvent(self, event):
rect = self.geometry()
size = min(rect.width(), rect.height())
movie = self.loading_lbl.movie()
movie.setScaledSize(QtCore.QSize(size, size))
self.loading_lbl.adjustSize()
def main():
app = QtGui.QApplication(sys.argv)
ex = MovieTest()
ex.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Ok I have this figured out now, with just a few tweaks to the code in my edited post. The secret is in keeping the label the full size of it's parent rect (in this case the size of the whole layout) and then scaling the movie within the label. Essentially you are internally scaling the movie, instead of having it automatically fill the contents of the label. From what I can tell this changes around the order of operations a bit and allows the movie to scale itself on render, instead of rendering the frame and then scaling it to the label size.
Working code:
import sys
from PyQt4 import QtGui, QtCore
class MovieTest(QtGui.QDialog):
def __init__(self):
super(MovieTest, self).__init__()
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
self.loading_lbl = QtGui.QLabel()
self.loading_lbl.setStyleSheet('border: 1px solid red') # just for illustration
self.loading_lbl.setAlignment(QtCore.Qt.AlignCenter)
layout.addWidget(self.loading_lbl)
loading_movie = QtGui.QMovie("loading-radial_loop.gif")
self.loading_lbl.setMovie(loading_movie)
loading_movie.start()
self.setGeometry(50,50,100,100)
self.setMinimumSize(10,10)
def resizeEvent(self, event):
rect = self.geometry()
size = QtCore.QSize(min(rect.width(), rect.height()), min(rect.width(), rect.height()))
movie = self.loading_lbl.movie()
movie.setScaledSize(size)
def main():
app = QtGui.QApplication(sys.argv)
ex = MovieTest()
ex.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

How to add image to QTextBrowser (PyQt4) using Python at a specific required point?

I am doing Text mining using python.
I created a GUI using QT and transformed it into python snippet using PyQt4.
I have QTextBrowser which indicates the sentiment index of the passage.
Based on the score of the sentiment index I want to add different images into the Qtextbrowser.
Below which I have added the screenshot of my tool.
https://drive.google.com/file/d/0B-bFVFevEa-yMUZUMnc2UWN4T00/edit?usp=sharing
Below image is the screenshot of the tool which I have created for Text mining.
At the the bottom of the right hand panel , you can see the score of sentiment of the passage.
Now I want to add the image on the highlighted square box area depending upon the score of the sentiment.
How to add the image at the particular point in the QtextBrowser ?
http://pyqt.sourceforge.net/Docs/PyQt4/qtextbrowser.html#loadResource
Example:
import sys
from PyQt4 import QtGui, QtCore
class myTextBrowser(QtGui.QTextBrowser):
def loadResource (self, type, name):
return QtGui.QPixmap("test.jpg")
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
a = myTextBrowser()
a.document().setHtml("""My image :<br /><img src="test.jpg"/>""")
a.show()
sys.exit(app.exec_())
import sys
import requests
from PyQt6 import QtGui, QtCore
class myTextBrowser(QtGui.QTextBrowser):
def loadResource (self, type, name):
pic_data = requests.get(name.url(), allow_redirects=True).content
pixmap = QPixmap()
pixmap.loadFromData(pic_data)
return pixmap
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
a = myTextBrowser()
a.setHtml("""My image :<br /><img src="img_url"/>""")
a.show()
sys.exit(app.exec_())

Categories