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

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)

Related

connecting toolbar icon to move stacked pages pyqt

I trying to connect my pyqt6 GUI app to move between stacked widget pages based on the icons you press in the toolbar. I saw that if i use the triggered method it suppose to work but for some reason when I run my python code, I always see the app on page 2 and not my default page 1 and the icons are not triggering movement to a different page. I checked the heirarchy of the elements that I built un the GUI in QT Designer and made sure there are two separate pages, you can see in the image below:
This is the code im running currently:
import sys
from PyQt6.QtWidgets import QApplication
from PyQt6.QtWidgets import QMainWindow
from app_try import Ui_MainWindow
class MainWindow:
def __init__(self):
self.main_win = QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.main_win)
def show_page(self, page):
print("showPage called with page", page)
self.ui.stackedWidget.setCurrentWidget(page)
self.ui.stackedWidget.setCurrentWidget(self.ui.page)
self.ui.action_send_info.triggered(lambda: self.show_page(self.ui.page))
print("Connected action_send_info to showPage")
self.ui.action_data_table.triggered(lambda: self.show_page(self.ui.page_2))
print("Connected action_data_table to showPage")
def show(self):
self.main_win.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
main_win = MainWindow()
main_win.show()
sys.exit(app.exec_())
app_try is the name of my python file which I import in order to get all the elemnts of the GUI. Am I missing something that i need to add in order for the icons to move between the page? thank you for any help!

PyQT drag and drop to reorder items

Im trying to make a small app that would help me rename pictures. Since i want to manually order them, i had the idea to simply show a window with thumbnails inside in a grid ( or small scale images, doesnt matter ), and then drag and drop reorder them as i see fit. Afterwards its just click a button and they get properly named acording to the order.
Is there any container or something that would allow its inside widgets to be moved around like that while also properly displaying the inside widgets?
The ways im thinking of currently since i cant find anything else, is to make the whole background a canvas, move x/y on drag/drop of the pictures and then calculate where im dropping it off and manually reorder the whole canvas again and keep redrawing.
Im open to different python solution if anyone has them, but after checking wxwidgets and tkinter, i havent found anything that would be a solution to this without a lot of manual code.
After ekhumoro hint, i was able to solve it.
Heres a sample code that reads the current folder of its files, shows them as "thumbnails", and allows reordering.
#!/usr/bin/python
import sys, os
from PyQt5.QtWidgets import (QListWidget, QWidget, QMessageBox,
QApplication, QVBoxLayout,QAbstractItemView,QListWidgetItem )
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtWidgets import QListView
class Example(QWidget):
def __init__(self):
super().__init__()
self.icon_size = 200
self.initUI()
def loadImageItem(self, fajl,folder=None):
icon = QIcon()
item = QListWidgetItem()
if folder is not None:
pot = os.path.join(folder,fajl)
else:
pot = fajl
icon.addFile(pot,size=QSize(self.icon_size,self.icon_size))
item.setIcon(icon)
item.setTextAlignment(Qt.AlignBottom)
return item
def initUI(self):
vbox = QVBoxLayout(self)
listWidget = QListWidget()
#make it icons
listWidget.setDragDropMode(QAbstractItemView.InternalMove)
listWidget.setFlow(QListView.LeftToRight)
listWidget.setWrapping(True)
listWidget.setResizeMode(QListView.Adjust)
listWidget.setMovement(QListView.Snap)
listWidget.setIconSize(QSize(200,200))
folder = os.getcwd()
#folder = "/mnt/Data/pictures/2022-10-30 Sveta Katarina/izbor/1"
files = os.listdir(folder)
files = [f for f in files if os.path.isfile(os.path.join(folder,f))]
for foo in files:
listWidget.addItem(self.loadImageItem(foo,folder=folder))
vbox.addWidget(listWidget)
self.setLayout(vbox)
self.setGeometry(10, 10, 1260, 820)
self.setWindowTitle('Image renamer')
self.show()
def main():
App = QApplication(sys.argv)
ex = Example()
sys.exit(App.exec())
if __name__ == '__main__':
main()

UI made in QT Designer shifts behind Title Bar [duplicate]

I'm trying to create an application that contains a web browser within it, but when I add the web browser my menu bar visually disappears but functionally remains in place. The following are two images, one showing the "self.centralWidget(self.web_widget)" commented out, and the other allows that line to run. If you run the example code, you will also see that while visually the entire web page appears as if the menu bar wasn't present, you have to click slightly below each entry field and button in order to activate it, behaving as if the menu bar was in fact present.
Web Widget Commented Out
Web Widget Active
Example Code
import os
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
class WebPage(QWebEngineView):
def __init__(self, parent=None):
QWebEngineView.__init__(self)
self.current_url = ''
self.load(QUrl("https://facebook.com"))
self.loadFinished.connect(self._on_load_finished)
def _on_load_finished(self):
print("Url Loaded")
class MainWindow(QMainWindow):
def __init__(self, parent=None):
# Initialize the Main Window
super(MainWindow, self).__init__(parent)
self.create_menu()
self.add_web_widet()
self.show()
def create_menu(self):
''' Creates the Main Menu '''
self.main_menu = self.menuBar()
self.main_menu_actions = {}
self.file_menu = self.main_menu.addMenu("Example File Menu")
self.file_menu.addAction(QAction("Testing Testing", self))
def add_web_widet(self):
self.web_widget = WebPage(self)
self.setCentralWidget(self.web_widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.showMaximized()
sys.exit(app.exec_()) # only need one app, one running event loop
Development Environment
Windows 10, PyQt5, pyqt5-5.9
EDIT
The problem doesn't seem to be directly related to the menu bar. Even removing the menu bar the issue still occurs. That said, changing from showMaximized() to showFullScreen() does seem to solve the problem.
I no longer believe this is an issue with PyQt5 specifically but rather a problem with the graphics driver. Specifically, if you look at Atlassian's HipChat application it has a similar problem which is documented here:
https://jira.atlassian.com/browse/HCPUB-3177
Some individuals were able to solve the problem by running the application from the command prompt with the addendum "--disable-gpu" but that didn't work for my python application. On the other hand, rolling back the Intel(R) HD Graphics Driver did solve my problem. Version 21.20.16.4627 is the one that seems to be causing problems.

Questions about Qt internationalization

I am having trouble figuring out how to use Qt to create translation files for a python apllication.
I'm using python 2.7, Qt version 5.9.1 and PyQt4 4.12.1 to create my GUI on OSX 10.11.6.
For now I just wanted to translate a few words on my code.
For what I understand, I have to use QtLinguist to open a .ts file, translate the words and create a .qm file, which will then be used by python.
From Qt Linguist page I get that I need to use a .pro project file, that will be read by pylupdate4, etc...
Now, I do I create a .pro file?
I tried running:
$ qmake -project myfile.py
$ pylupdate4 myfile.pro -ts file.ts
but the resulting .pro file can't be read by pylupdate4 (XML error: Parse error at line 1, column 1 [...])
From this Tutorial, I tried:
$ pylupdate4 myfile.py -ts file.ts
Which creates an empty .ts file, that Qt Linguist can't open.
Can someone give my any tip on what might be wrong, the 15 tabs I have open in my browser are not helping.
Here's my python code if you need it:
import sys
import os.path as osp
import os
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow,self).__init__()
# Set MainWindow geometry, use settings of last session. If it's first session,
# use defaulted settings
self.settings = QtCore.QSettings('Paul',QtCore.QSettings.NativeFormat)
self.resize(self.settings.value("size", QtCore.QSize(500, 300)).toSize())
self.move(self.settings.value("pos", QtCore.QPoint(5, 5)).toPoint());
self.initUI()
def closeEvent(self, e):
#Save MainWindow geometry session when closing the window
self.settings.setValue("size",self.size())
self.settings.setValue("pos",self.pos())
e.accept()
def initUI(self):
self.hbox = QtGui.QVBoxLayout(self) # Create Vertival box layout to put the buttons
self.myButtons = QtGui.QPushButton('button',self) #create push button
self.myButtons.setStyleSheet("""QPushButton { background-color: red; font:bold 20px}""")
self.myButtons.setToolTip('Push this button')
self.myButtons.setText(self.tr(QtCore.QString('yes')))
comboBox=QtGui.QComboBox(self) #create drop down menu
comboBox.addItem('Portugues')
comboBox.addItem('English')
self.hbox.addWidget(comboBox,1,QtCore.Qt.AlignRight) #add drop down menu to box layout
self.hbox.addStretch(3) # set separation between buttons
self.myButtons.clicked.connect(self.buttonClicked) # what should the button do
self.hbox.addWidget(self.myButtons,1,QtCore.Qt.AlignRight) #add button to box layout
self.setWindowTitle('Test2')
self.show()
def buttonClicked(self):
msbox= QtGui.QMessageBox()
choice=msbox.warning(self,'ok',"This button doesn't do anything!!!")
if choice == QtGui.QMessageBox.No:
print('nanan')
else:
print('Bye')
self.settings.setValue("size",self.size());
self.settings.setValue("pos",self.pos());
sys.exit()
def main():
app = QtGui.QApplication(sys.argv)
translator = QtCore.QTranslator()
translator.load("~/basefiles/translations/qt_pt.qm")
app.installTranslator(translator)
ex = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
When you use self.tr you must pass the string, not the QString variable, in your case it changes:
self.myButtons.setText(self.tr(QtCore.QString('yes')))
to
self.myButtons.setText(self.tr("yes"))
And run everything again.

Display an image when pressing a button in Qt GUI (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())

Categories