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
Related
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 ?
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 would like to add a QCheckBox to a QFileDialog. I would like to use the static method QFileDialog.getSaveFileName() to show the dialog.
I have found several similar questions, all in c++:
How to add checkbox to QFileDialog window in QT3?
Adding a widget in QFileDialog
https://www.qtcentre.org/threads/42858-Creating-a-Custom-FileOpen-Dialog
https://forum.qt.io/topic/103964/add-checkbox-to-qfiledialog/7
I did my best to translate these discussions to python, but have not gotten to the solution yet. My code runs, but the checkbox does not show up, even when I use QFileDialog.DontUseNativeDialog.
This is how I am subclassing QFileDialog:
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtWidgets import QCheckBox
class ChkBxFileDialog(QFileDialog):
def __init__(self, chkBxTitle=""):
super().__init__()
self.setOption(QFileDialog.DontUseNativeDialog)
chkBx = QCheckBox(chkBxTitle)
self.layout().addWidget(chkBx)
#end __init__
#end ChkBxFileDialog
I have run this in two ways.
Option 1 (with extra QFileDialog.DontUseNativeDialog):
import sys
from PyQt5.QtWidgets import QApplication
if __name__ == "__main__":
app = QApplication(sys.argv)
fileDialog = ChkBxFileDialog(chkBxTitle="Chkbx")
fileName = fileDialog.getSaveFileName(filter='*.txt', initialFilter='*.txt',
options=QFileDialog.DontUseNativeDialog)[0]
sys.exit(app.exec_())
Option 2 (without extra QFileDialog.DontUseNativeDialog):
import sys
from PyQt5.QtWidgets import QApplication
if __name__ == "__main__":
app = QApplication(sys.argv)
fileDialog = ChkBxFileDialog(chkBxTitle="Chkbx")
fileName = fileDialog.getSaveFileName(filter='*.txt', initialFilter='*.txt')[0]
sys.exit(app.exec_())
The checkbox doesn't show with either option. Option 1 uses different window styling. Option 2 shows the typical PyQt QFileDialog.
Does anyone know what I am missing?
The problem is that getSaveFileName is a static method so they do not inherit from ChkBxFileDialog and therefore do not have the custom behavior.
There are 2 options:
Don't use getSaveFileName but implement the logic using QFileDialog directly:
import sys
from PyQt5.QtWidgets import QApplication, QCheckBox, QDialog, QFileDialog
class ChkBxFileDialog(QFileDialog):
def __init__(self, chkBxTitle="", filter="*.txt"):
super().__init__(filter=filter)
self.setSupportedSchemes(["file"])
self.setOption(QFileDialog.DontUseNativeDialog)
self.setAcceptMode(QFileDialog.AcceptSave)
self.selectNameFilter("*.txt")
chkBx = QCheckBox(chkBxTitle)
self.layout().addWidget(chkBx)
def main():
app = QApplication(sys.argv)
dialog = ChkBxFileDialog()
if dialog.exec_() == QDialog.Accepted:
filename = dialog.selectedUrls()[0].toLocalFile()
print(filename)
if __name__ == "__main__":
main()
Use some trick to get the QFileDialog instance, such as getting all the topLevels and verifying that it is a QFileDialog.
import sys
from functools import partial
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QCheckBox, QDialog, QFileDialog
def add_checkbox(chkBxTitle):
for tl in QApplication.topLevelWidgets():
if isinstance(tl, QFileDialog):
tl.setOption(QFileDialog.DontUseNativeDialog)
chkBx = QCheckBox(chkBxTitle)
tl.layout().addWidget(chkBx)
def main():
app = QApplication(sys.argv)
QTimer.singleShot(1000, partial(add_checkbox, ""))
fileName, _ = QFileDialog.getSaveFileName(
filter="*.txt", initialFilter="*.txt", options=QFileDialog.DontUseNativeDialog
)
if __name__ == "__main__":
main()
I would like to use the static method QFileDialog.getSaveFileName() to show the dialog
That's not possible. The static method as is defined in the C++ code knows nothing about your derived class, so it will create an instance of the base class, which doesn't contain your modifications. You have to explicitly instantiate your derived class, call exec() on the instance, check the return code and possibly call its selectedFiles() method to see what files were selected.
I am making a custom console/shell window module using pyqt5 I have basically everything working but when I import it the whole entire script freezes because of a loop in the module that I import.
This is the module that gets imported:
import sys
import time
from PyQt5 import QtWidgets, uic
from PyQt5.QtCore import QRunnable, QThreadPool
from PyQt5.QtWidgets import QTextEdit
class SpamWorker(QRunnable):
def __init__(self, console: QTextEdit):
super().__init__()
self.console = console
def run(self):
while True:
time.sleep(0.2)
self.console.append('SPAM!')
class Printer(QtWidgets.QMainWindow, QRunnable):
def __init__(self):
super(Printer, self).__init__()
uic.loadUi('window.ui', self)
self.setWindowTitle("Console+")
self.thread_pool = QThreadPool()
self.thread_pool.start(SpamWorker(self.Console))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Printer()
window.show()
sys.exit(app.exec_())
how can I import it without it freezing?
What I am ultimately trying to accomplish is to capture the username and password that the user enters into a website. For example, if the user enters "test#example.com" as the email address into Facebook's login, then clicks submit, I want to store that email address in my PyQt Application.
The closest I've come to achieving this has been using a series of JavaScript commands to place a listener on the "Login Button" that returns the current value of the user parameter. My problem is that the callback that PyQt provides is for when the runJavaScript function is completed, not the javascript event listener. I'm wondering if there is any way to capture the callback function from the JavaScript function, or if there is a better way altogether for me to do this.
import os
import sys
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget
from PyQt5.QtCore import QUrl, QEventLoop
from PyQt5.QtWebEngineWidgets import QWebEngineView
class WebPage(QWebEngineView):
def __init__(self):
QWebEngineView.__init__(self)
self.load(QUrl("https://facebook.com"))
self.loadFinished.connect(self._on_load_finished)
#self.page().runJavaScript("document.getElementById("myBtn").addEventListener("click", displayDate)", print)
def _on_load_finished(self):
print("Finished Loading")
cmds = ["btn=document.getElementById('u_0_r')", # Login Button
"user=document.getElementsByName('email')[0]",
"function get_username(){return user.value}",
"btn.addEventListener('click', get_username)"]
self.page().runJavaScript("; ".join(cmds), lambda x: print("test: %s" % x))
if __name__ == "__main__":
app = QApplication(sys.argv)
web = WebPage()
web.show()
sys.exit(app.exec_()) # only need one app, one running event loop
I found a work around using the "urlChanged" signal that seems to work so far for my applications
import os
import sys
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget
from PyQt5.QtCore import QUrl, QEventLoop
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInterceptor
class WebPage(QWebEngineView):
def __init__(self):
QWebEngineView.__init__(self)
self.current_url = ''
self.load(QUrl("https://facebook.com"))
self.loadFinished.connect(self._on_load_finished)
self.urlChanged.connect(self._on_url_change)
def _on_load_finished(self):
self.current_url = self.url().toString()
def _on_url_change(self):
self.page().runJavaScript("document.getElementsByName('email')[0].value", self.store_value)
def store_value(self, param):
self.value = param
print("Param: " +str(param))
if __name__ == "__main__":
app = QApplication(sys.argv)
web = WebPage()
web.show()
sys.exit(app.exec_()) # only need one app, one running event loop