I wanted to create a browsing media file with QT so I wrote that :
import sys
import random
import os
import time
from PyQt6 import QtCore, QtWidgets, QtGui
from PyQt6.QtWidgets import QLabel, QPushButton,QSizePolicy, QFileDialog,QHBoxLayout, QVBoxLayout, QSlider, QInputDialog, QMainWindow, QApplication
from PyQt6.QtGui import QPixmap, QShortcut, QKeySequence, QMovie
from PyQt6.QtCore import Qt,QUrl, QTimer, QSettings, QSize, QPoint
from PyQt6.QtMultimediaWidgets import QVideoWidget
from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput
# Subclass QMainWindow to customize your application's main window
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.posi = 0
#path
if (len( sys.argv ) > 1):
self.folderpath = sys.argv[1]
else:
self.folderpath = "your folder contaianing the files" #<============ DONT FORGET TO FINISH THE PATH WITH /
#pathlist
self.img_list = os.listdir(self.folderpath)
print(self.img_list)
self.setWindowTitle("My App")
self.mediaPlayer = QMediaPlayer(None)
self.videoWidget = QVideoWidget()
self.audio_output = QAudioOutput()
self.mediaPlayer.setVideoOutput(self.videoWidget)
self.mediaPlayer.setAudioOutput(self.audio_output)
self.audio_output.setVolume(50)
self.mediaPlayer.setLoops(-1)
self.mediaPlayer.setSource(QUrl(self.folderpath+self.img_list[0]))
self.mediaPlayer.play()
# Set the central widget of the Window.
self.setCentralWidget(self.videoWidget)
#shortcut
self.shortcut_right = QShortcut(QKeySequence("Right"),self)
self.shortcut_right.activated.connect(self.button_right_clicked)
def button_right_clicked(self, *args):#when navigate right
print("---->")
try:
self.img_list[self.posi+1]
except IndexError:
self.posi = 0
else:
self.posi = self.posi + 1
self.mediaPlayer.setSource(QUrl(self.folderpath+self.img_list[self.posi]))
self.mediaPlayer.play()
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
But sometimes when use the method "button_right_clicked" the program shutdown without any error or closing event. This method is used to navigate through the list of files in the source folder. I'm using only mp4 file for now.
The error comes from this line i presume : self.mediaPlayer.setSource(QUrl(self.folderpath+self.img_list[self.posi]))
Because when i try to set the same media (img_list[0]) file as source, instead of using index self.posi, it doesn't crash.
According to the documentation, it seems to be the approriate way of swapping between media.
Any idea how to solve this problem ?
Related
hello world i am trying to get a QLineEdit to work as a user Input witch they are suppose to type in a song name. after the song name is entered i am wanting that song to start playing after the click the play button everything is working fine other then the part where they can type in what ever song they want in that folder. the problem is im not sure on how to make the QlineEdit word and update everytime someone thing is entered into the text box here is my code hopefully someone can help me out Thanks in advance!
import sys
import webbrowser
import random
import time
import os
import subprocess
from PyQt4.QtCore import QSize, QTimer, SIGNAL
from PyQt4.QtGui import QApplication,QScrollBar,QLineEdit , QDialog , QFormLayout ,QGraphicsRectItem , QMainWindow, QPushButton, QWidget, QIcon, QLabel, QPainter, QPixmap, QMessageBox, QAction, QKeySequence, QFont, QFontMetrics, QMovie
from PyQt4 import QtGui
import vlc
#----|Imports End|----#
class UIWindow(QWidget):
def __init__(self, parent=None):
super(UIWindow, self).__init__(parent)
self.resize(QSize(400, 450))
self.Play = QPushButton('Play', self)
self.Play.resize(100,40)
self.Play.move(45, 100)#
self.Pause = QPushButton('Pause', self)
self.Pause.resize(100,40)
self.Pause.move(260, 100)#
self.Tbox = QLineEdit('Song name',self)
self.Tbox.resize(400,25)
self.Tbox.move(0,50)
self.Play.clicked.connect(self.PlayB)
self.Pause.clicked.connect(self.PauseB)
self.Flask = vlc.MediaPlayer("C:\Users\Matt\Music\\"+str(self.Tbox.text())+".mp3")
def PlayB(self):
self.Flask.play()
def PauseB(self):
self.Flask.stop()
class MainWindow(QMainWindow,):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setGeometry(745 ,350 , 400, 450)
self.setFixedSize(400, 450)
self.startUIWindow()
def startUIWindow(self):
self.Window = UIWindow(self)
self.setWindowTitle("HELP ME!")
self.setCentralWidget(self.Window)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
sys.exit(app.exec_())
You can easily get text with QLineEdit.text() method.
Or same way set text with QLineEdit.setText() method
If you want to connect it to QTextEdit You can connect it with .textChanged signal which is emited from QTextEdit everytime text changes.
The same way how you use .clicked signal you can use this one as:
QTextEdit.textChanged.connect(your_method_to_put_text_somewhere_else)
I am developing a PyQt5 application however I am having issues with the heights of the widgets. Below is a simplified version of my issue:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class App(QWidget):
def __init__(self):
super().__init__()
self.showMaximized()
self.setStyleSheet("QWidget {background: blue;}")
print(self.frameGeometry().height())
self.show()
if __name__ == "__main__":
window = QApplication(sys.argv)
app = App()
window.setStyle(QStyleFactory.create("Fusion"))
window.exec_()
Here I create a window and maximise it. Using a tkinter window, it tells me the height maximised is 841, which is the size of my screen, however the PyQt5 application prints the height to be 519. Is this an issue with the self.showMaximized() method, or some other issue.
Resizing is not instantaneous in Qt. What Qt does is take the information from showMaximized to activate the flag of the native window (library that depends on each OS) then after a time T the OS applies that flag and sends it the new geometry. So in your case you have to give it a delay to get the correct information.
import sys
from PyQt5.QtWidgets import QApplication, QStyleFactory, QWidget
from PyQt5.QtCore import QTimer
class App(QWidget):
def __init__(self):
super().__init__()
self.setStyleSheet("QWidget {background: blue;}")
self.showMaximized()
QTimer.singleShot(100, self.calculate)
def calculate(self):
print(self.frameGeometry().height())
if __name__ == "__main__":
window = QApplication(sys.argv)
app = App()
window.setStyle(QStyleFactory.create("Fusion"))
window.exec_()
On the other hand, if your objective is to know the size of the initial screen then you should not use a QWidget for that since it will depend on the time it takes for Qt and the native library to create the native window, instead use the Screen class :
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QGuiApplication
if __name__ == "__main__":
window = QApplication(sys.argv)
print(QGuiApplication.primaryScreen().availableGeometry().height())
Icons are not showing in my QListWidgetItems.
Edit 2:
Turns out you can't use absoulte path. You must use relative path. But why is this the case?
Minimum reproducible example:
import json
import os
import sys
from math import floor
from PyQt5 import QtTest, QtGui
from PyQt5.QtDesigner import QFormBuilder
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QFrame, QGridLayout, QLabel, QMainWindow, QScrollArea, QWidget, QVBoxLayout, \
QListView, QListWidget, QListWidgetItem, QToolButton
from PyQt5.QtCore import QPoint, Qt, QIODevice, QFile
from PyQt5.Qt import QPixmap
class MainWindow(QMainWindow):
def __init__(self, *args, obj=None, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
#ListWidget
listWidget = QListWidget(self)
listWidget.setViewMode(QListWidget.IconMode)
listWidget.setFixedSize(500, 700)
dir = r'Players'
for filename in os.listdir(dir):
#Item
item = QListWidgetItem(QIcon('Players/Pogba.jpg'), '<Name>', listWidget)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.showMaximized()
app.exec_()
I followed the docs(https://doc.qt.io/qt-5/qlistwidgetitem.html), so why are they not appearing?
Edit:
It looks like it only happens when the image is outside the source code's folder. Why is this the case?
I have a strange problem, hope someone can clear it for me
import os
from os import path
import sys
import pathlib
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget,
QWizard, QWizardPage, QLineEdit, \
QTabWidget, QApplication,
QTextEdit,QToolTip,QPushButton,QMessageBox
from PyQt5.QtCore import QSize,pyqtSlot,pyqtProperty
from PyQt5.QtGui import QFont
from PyQt5.uic import loadUiType
app = QApplication(sys.argv)
if getattr(sys, 'frozen', False):
# we are running in a bundle
installPath = sys._MEIPASS
print('we are running in a bundle')
else:
# we are running in a normal Python environment
installPath = os.path.dirname(os.path.abspath(__file__))
print('we are running in a normal Python environment')
UI_File, _ = loadUiType(path.join(path.dirname(__file__), 'test.ui'))
class MainAPP(QTabWidget, UI_File):
def __init__(self, parent=None):
super(MainAPP, self).__init__(parent)
self.setupUi(self)
self.handle_buttons()
def handle_buttons(self):
self.pushButton.clicked.connect(self.test_2)
def test_2(self):
for i in range(10):
self.listWidget.addItem(str('lklk'))
self.listWidget.itemClicked.connect(self.test)
def test(self):
for i in range(10):
self.listWidget_2.addItem(str('DDD'))
self.listWidget_2.itemClicked.connect(self.test_3)
def test_3(self):
print ('hi')
def main():
app = QApplication(sys.argv)
main = MainAPP()
main.show()
app.exec_()
if __name__ == "__main__":
main()
so basically, I have a push button, if I click on it it will display some data at listWidget and if I clicked on any item in listWidget , it will display other data on ListWidget_2 and then if I click on item in List_widget_2 it then should print ('Hi')
the problem is if I click multiple times in ListWidget and then click on an item in ListWidget_2 , I received more than one ('Hi) , it will diplay ('Hi') according to the number of clicks I clicked in the Listwidget
any idea what could be the issue
You only need to make a connection between a signal and a slot once. Currently you are making additional connections each time you click an item in the first list widget, which results in your method printing "hi" executing once for every connection you made.
To fix this, make both of the signal connections either in the test_2 method or in the __init__ method
I have a form with a picture on it, in this example it is a Humidity Indicator the user should be able to press the 60, 10 and 5% spot. The label should display the pressed spot.
How do I do that could somebody show me an example or is this not possible with Qt?
My code (which is pretty empty for now)
from PyQt5.QtWidgets import QApplication, QWidget, QDialog
from PyQt5.QtGui import QPixmap, QRegExpValidator
from PyQt5.QtCore import QRegExp
from mysql.connector import (connection)
from datetime import *
from bs4 import BeautifulSoup as bs
import os
import sys
import DatabaseHandling
'''Convert UI file to Python'''
os.chdir("C:\\Users\Gianni Declercq\AppData\Local\Programs\Python\Python36-32\Scripts")
os.system("pyuic5.exe M:\QtProjects\\Ui\RPI1_Third.ui -o M:\QtProjects\\RPI1_Third_ui.py")
from RPI1_Third_ui import Ui_Form3 # import after recreation of py file
class ThirdWindow(QWidget, Ui_Form3):
def __init__(self):
super(ThirdWindow, self).__init__()
self.dbu = DatabaseHandling.DatabaseUtility()
self.msl = None
# Show UI on screen + resize window
self.setupUi(self)
self.picInidicator.setPixmap(QPixmap("F:\QtProjects\\138691.jpg"))
self.setFixedSize(800, 480)
if __name__ == '__main__':
app = QApplication([])
window = ThirdWindow()
window.show()
sys.exit(app.exec_())
Example of the form