In PyQT4 there is a QLabel()
While when I use it in PyQT5 it throws an undefined error.
Can anyone one tell me what is Qlabel in the PyQT4 ?
Or maybe I am wrong?
Here is my code:
import sys
import time
from PyQt5.QtCore import *
from PyQt5.QtGui import *
app = QGuiApplication(sys.argv)
try:
due = QTime.currentTime()
message = "Alert!"
if len(sys.argv) < 2 :
raise ValueError
hours, min = sys.argv[1].split(":")
due = Qtime(int(hours), int(min))
if not due.isValid():
raise ValueError
if len(sys.argv) > 2 :
message = " ".join(sys.argv[2:])
except ValueError :
message = "Alert: alert.pyw"
if QTime.currentTime() < due :
time.sleep(20) #20 Seconds
label = QLabel("<p>Message</p>")
You should read the docs I posted. Add this import statement with the others:
from PyQt5.QtWidgets import *
Because QLabel() is in PyQt5.QtWidgets, please try following :
from PyQt5.QtWidgets import QLabel
Related
Here if I run the code with components() line commented out I get a window with a purple torus as expected but if I just call the components() on the torus_entity (uncomment the line) the torus disappears.
I can print the components from the components() but trying to usem them returns an error saying it was deleted, for example: deleted torus_mesh.
The material variable which can be reused for various models also throws error saying the material was deleted if you try to use it on any line beyond the components() call.
Qt documentation: https://doc.qt.io/qt-5/qt3dcore-qentity.html#components
Documentation says components returns a list of QComponent nothing about the deletion, I don't know how to use this properly?
I'd like to go through the components and check them and change their properties, for example change position and/or scale through QTransform component.
I could go down the QT version to 5.12.12 but I don't know how to do this for PyQt5 so it builds against this QT version.
I've tried it in PyQt6, also in Qt5 (c++, but different version then the PyQt5 uses) and it works just fine in both, this might be a bug in PyQt5/Qt5? I wonder if there's a workaround for this (maybe making adjustments in some PyQt5 files?)?
import sys
from PyQt5.Qt3DCore import QEntity, QTransform, QAspectEngine
from PyQt5.QtCore import QPropertyAnimation, QVariant, QUrl
from PyQt5.QtGui import QVector3D, QQuaternion, QGuiApplication, QColor
from PyQt5.Qt3DRender import QCamera, QCameraLens, QRenderAspect, QDirectionalLight, QSceneLoader
from PyQt5.Qt3DInput import QInputAspect
from PyQt5.Qt3DExtras import QForwardRenderer, QMetalRoughMaterial, QCylinderMesh, QSphereMesh, QTorusMesh, \
Qt3DWindow, QOrbitCameraController, QPlaneMesh
def create_scene():
root_entity = QEntity()
d_light_entity = QEntity(root_entity)
direction_light = QDirectionalLight()
direction_light.setColor(QColor(255, 254, 245))
direction_light.setIntensity(2)
d_light_entity.addComponent(direction_light)
material = QMetalRoughMaterial(root_entity)
material.setBaseColor(QColor(160, 30, 160))
material.setRoughness(.5)
# Torus
torus_entity = QEntity(root_entity)
torus_mesh = QTorusMesh()
torus_mesh.setRadius(5)
torus_mesh.setMinorRadius(1)
torus_mesh.setRings(100)
torus_mesh.setSlices(20)
torus_transform = QTransform()
torus_transform.setScale3D(QVector3D(1.5, 1, 0.5))
torus_entity.addComponent(torus_mesh)
torus_entity.addComponent(torus_transform)
torus_entity.addComponent(material)
#components = torus_entity.components()
return root_entity
def main(argv):
app = QGuiApplication(argv)
view = Qt3DWindow()
view.defaultFrameGraph().setClearColor(QColor(39, 39, 39))
scene = create_scene()
camera = view.camera()
camera.lens().setPerspectiveProjection(45.0, 15.0/9.0, .1, 1000.0)
camera.setPosition(QVector3D(0, 0, 40.0))
camera.setViewCenter(QVector3D(0, 0, 0))
view.setRootEntity(scene)
view.show()
return sys.exit(app.exec())
if __name__ == '__main__':
main(sys.argv)
I have a code that display Items in a QlistWidget that refer to a file path once the user select one of the items the system display its content.
The problem is that once the user select one of the item it keep the focus on it and the user can't select other item.
the Image below show that both items have focus that mean when i try to select the second Item i must deselect the first and vise versa.
How to fix this?
example :
C:\Users\test\Desktop\New Microsoft Word Document.docx row =>0
C:\Users\test\Desktop\test_arabic.docx row =>1
the displayed result on the console :
current row = 0 this is P==>C:\Users\test\Desktop\test_arabic.docx
this is oneDir==>C:\Users\test this is the cuurent Item
==C:\Users\test\Desktop\New Microsoft Word Document.docx
current row = 1 this is P==>C:\Users\test\Desktop\test_arabic.docx
this is oneDir==>C:\Users\test this is the cuurent Item
==C:\Users\test\Desktop\New Microsoft Word Document.docx
and if the user select twice the same item the system display this error :
mouseHover toolTipResult = self.listWidgetPDFlist.setToolTip(Item)
builtins.UnboundLocalError: local variable 'Item' referenced before
assignment
code:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import (QMimeData)
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton, QMenu,QListWidgetItem)
#from PyQt5.QtCore import QDir, Qt
from PyQt5.QtWidgets import *
import pdfviewer
import pathlib
from pathlib import Path
import os
import re
from os import path
import json,datetime,time
from collections import defaultdict
import docx
import PyPDF2
class pdfViewer(pdfviewer.Ui_PdfPreviewWindow):
def __init__(self,PdfPreviewObj):
pdfviewer.Ui_PdfPreviewWindow.__init__(self)
self.PdfPreviewObj =PdfPreviewObj
self.setupUi(PdfPreviewObj)
self.PdfPreviewObj.show()
'''
buttons status at the init of the program
'''
self.pushButtonSearch.setEnabled(False)
rMyIcon = QtGui.QPixmap("checkBox.ico");
self.SelectAll.setIcon(QtGui.QIcon(rMyIcon))
self.SelectAll.setEnabled(False)
self.pushButtonOpenFolder.clicked.connect(self.openfolder)
self.ExportButton.clicked.connect(self.openExport)
self.pushButtonSearch.clicked.connect(self.FilteredListSearch)
self.listWidgetPDFlist.clicked.connect(self.MatchFunc)
self.listWidgetPDFlist.doubleClicked.connect(self.OpenTheSelectedFile)
#self.NewClearList.clicked.connect(self.NewClearListFN)
self.SelectAll.clicked.connect(self.selectAllFN)
def mouseHover(self):
p = pathlib.Path(self.fullPath)
print("MouseHover this is P==>{}".format(p))
oneDir = os.path.join(*p.parts[:-2])
print("MouseHover this is oneDir==>{}".format(oneDir))
if self.listWidgetPDFlist.selectedItems():
Item = oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[0].text()
print("MouseHover this is the cuurent Item =={}".format(Item))
self.listWidgetPDFlist.setStyleSheet("""QToolTip {
background-color: black;
color: white;
border-radius: 10px;
border: black solid 1px;
font: 12px
}""")
print("current row = {}".format(self.listWidgetPDFlist.currentRow()))
toolTipResult = self.listWidgetPDFlist.setToolTip(Item)
return toolTipResult
def FileListSelected(self): # Function to select the desired file from the list in the left pane
self.mouseHover()
p = pathlib.Path(self.fullPath)
print("this is P==>{}".format(p))
oneDir = os.path.join(*p.parts[:-2])
print("this is oneDir==>{}".format(oneDir))
if self.listWidgetPDFlist.selectedItems():
Item = oneDir + "\\" + self.listWidgetPDFlist.selectedItems()[0].text()
print("this is the cuurent Item =={}".format(Item))
return Item
else:
print("<b>!!! NO SELECTED FILE !!!</b>\n")
def checkPath(self,folder): # Funtion to check the given path for the wanted extension (Files)
try:
directory=folder
whichChecked=""
for root,dirs,files in os.walk(directory):
for filename in files:
if len(self.lineEdit_Ext.text())>0:
self.lineEdit_Ext.setStyleSheet("background-color:white")
self.lineEdit_Ext.setPlaceholderText("Enter The Filetype Extention Here")
if filename.endswith(self.lineEdit_Ext.text()):
fullPath=os.path.join(root,filename)
print(fullPath)
self.fileList.append(fullPath)
elif self.rdBtn_txt.isChecked() and filename.endswith("txt"):
fullPath=os.path.join(root,filename)
self.fileList.append(fullPath)
whichChecked="txt Ext was Selected"
elif self.rdBtn_pdf.isChecked() and filename.endswith("pdf"):
fullPath=os.path.join(root,filename)
self.fileList.append(fullPath)
whichChecked="pdf Ext was Selected"
elif self.rdBtn_docx.isChecked() and filename.endswith("docx") or filename.endswith("doc") :
self.fullPath=os.path.join(root,filename)
p = pathlib.Path(self.fullPath)
oneDir = os.path.join(*p.parts[-2:])
self.fileList.append(oneDir)
#self.fileList.append(self.fullPath)
whichChecked="docx - doc Ext was Selected"
if len(self.fileList) > 0:
self.lineEdit_Ext.setStyleSheet("bacground-color:white;")
self.lineEdit_Ext.setPlaceholderText("{0}".format(whichChecked))
else:
self.lineEdit_Ext.setStyleSheet("background-color:Red")
self.lineEdit_Ext.setPlaceholderText("No Ext is Specified")
self.ListFilesInViewer(self.fileList) # add the list into the listWidgetPDFlist
self.pushButtonSearch.setEnabled(True)
self.SelectAll.setEnabled(True)
return folder
except Exception as e:
print("this error occure {0}".format(e))
I'd guess you have listWidgetPDFlist set to selectionMode MultipleSelection where you want SingleSelection. This can be changed in Qt Designer or via code as the following example shows.
import sys
from PyQt5 import QtWidgets
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QListWidget()
for i in range(10):
w.addItem('Item {}'.format(i))
# w.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) # Multiple selection via control key
# w.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection) # Multiple selection (click toggle)
w.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) # Single selection
w.show()
sys.exit(app.exec_())
I am trying to ideally download thousands of PDF from a given website. However, for some reason it won't even download 100 PDF's. I am not sure why. Here is the code:
#!/usr/bin/env python
import time
from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from xhtml2pdf import pisa
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import*
from PyQt4.QtWebKit import *
class Foo(QWidget):
def __init__(self, parent=None):
super(Foo, self).__init__(parent)
self.count = -1
text_file = open("input.txt", "r")
self.params = text_file.read().split('\n')
self.url = 'http://www.asdfasdfasdf.com/Property.aspx?mode=details&pin={0}'
self.gridLayout = QGridLayout(self)
#self.tabWidget = QTabWidget(self)
#self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
self.mapper = QSignalMapper(self)
self.mapper.mapped.connect(self.on_mapper_mapped)
for i in range(100):
grabber = QWebView()
grabber.loadFinished.connect(self.mapper.map)
self.mapper.setMapping(grabber, i)
#self.tabWidget.addTab(grabber, "opener {0}".format(str(i)))
grabber.loadFinished.emit(True)
#pyqtSlot(int)
def on_mapper_mapped(self, gNumber):
self.count += 1
if self.count < len(self.params):
#gParam = self.params[self.count]
gParam = self.params[self.count]
opener = self.mapper.mapping(gNumber)
opener.load(QUrl(self.url.format(gParam)))
printer = QPrinter()
#setting format
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
#export file as c:\tem_pdf.pdf
PIDString = gParam[:2] + '-' + gParam[2:4] + '-' + gParam[4:7] + '-' + gParam[7:10] + '-' + gParam[10:14]
printer.setOutputFileName(PIDString + '.pdf')
def convertIt():
opener.print_(printer)
QObject.connect(opener, SIGNAL("loadFinished(bool)"), convertIt)
print str(self.count) + ' of ' + str(len(self.params))
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = Foo()
#main.show()
app.exec_()
sys.exit
Ideally I would like to add a footer as well but it bugs out if I try to do that. Input.txt has 100 numbers ( just for test, I need it to work on 85000). It works on real small numbers like 5 or 10 but won't do 100. Is there a limit to the QwebView instance? Should I manage that in order to make it work?
When I run this code for 100 PDF, it will print out 20 PDFS. If i Change the range to something smaller than 100, it will have duplicate PDF's but certainly more than 20.
Also, I get this error:
qpainter::begin: returned false
I think since you are trying to make a "PyQt Application" you should firstly make use of what it offers your.
Try have some look into it QNetworkAccessMAnager to have control of all your requests and all else, QNetworkRequest, QNetworkReply.
It will even take care of your threads and have your parallelism as desired. It won't freeze your app while it's being downloaded.
Have a small look into this code of mine. It doesn't do exactly what you want but is kinda a really good filtered example for what you need to have all set up.
# Subclass QNetworkAccessManager Here
from PyQt5.QtCore import QByteArray
from PyQt5.QtCore import QFile, pyqtSlot
from PyQt5.QtCore import QIODevice
from PyQt5.QtCore import QUrl
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtNetwork import QNetworkAccessManager
from PyQt5.QtNetwork import QNetworkRequest
class NetworkAccessManager(QNetworkAccessManager):
signal_add_image = pyqtSignal()
dialog = None
download_finished = False
message_buffer = None
reply = None
def __init__(self):
QNetworkAccessManager.__init__(self)
self.reply = self.get(QNetworkRequest(QUrl("")))
# Save image data in QByteArray buffer to the disk (google_image_logo.png
# in the same directory)
#pyqtSlot()
def slot_finished(self):
image_file = QFile("resources/browser_images/image_required_browser")
if image_file.open(QIODevice.ReadWrite):
image_file.write(self.message_buffer)
image_file.close()
self.signal_add_image.emit()
# QMessageBox.information(None, "Hello!", "File has been saved!")
else:
pass
# QMessageBox.critical(None, "Hello!", "Error saving file!")
self.download_finished = True
self.dialog.close()
# Append current data to the buffer every time readyRead() signal is
# emitted
#pyqtSlot()
def slot_read_data(self):
self.message_buffer += self.reply.readAll()
def request_image(self, url, progress_bar, dialog):
self.reply.deleteLater()
self.download_finished = False
self.dialog = dialog
self.message_buffer = QByteArray()
url = QUrl(url)
req = QNetworkRequest(url)
req.setRawHeader(b'User-Agent',
b'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36')
self.reply = self.get(req)
self.reply.readyRead.connect(self.slot_read_data)
self.reply.finished.connect(self.slot_finished)
self.reply.downloadProgress.connect(progress_bar)
def get_reply(self):
return self.reply
def done(self):
return self.download_finished
def set_reply(self, reply):
self.reply = reply
def del_reply(self):
self.reply.deleteLater()
NETWORK_ACCESS_MANAGER = NetworkAccessManager()
Hope it brings you some light ")
Im trying to compile this Python3.3-Code provided by:
http://www.youtube.com/watch?v=fqK8N48kPXs&feature=c4-overview-vl&list=PLA955A8F9A95378CE
I have installed QT 4.8.4 VS2012, PySide 1.1.2, python 3.3, Qt 5
import sys
from PySide.QtCore import *
from PySide.QtGui import *
import time
app = QApplication(sys.argv)
try:
#Default Values
due = QTime.currentTime()
message = "Alert!"
if len(sys.argv) < 2:
raise ValueError
hours, minutes = sys.argv[1].split(":")
due = QTime(int(hours), int(minutes))
if not due.isValid():
raise ValueError
if len(sys.argv) > 2:
message = " ".join(sys.argv[2:])
#python firstTutorial.py 15:36 This is my message
except ValueError:
message = "Usage: firstTutorial.py HH:MM [optional message]" #24 hour clock
while QTime.currentTime() < due:
time.sleep(10)
label = QLabel("<font color=red size=72><b>" + message + "</b></font>")
label.setWindowFlags(Qt.SplashScreen) #Keine Fenstereigenschaften nutzen
label.show()
QTimer.singleShot(20000, app.quit) #20 seconds till quit SIGNAL/SLOT
app.exec_()
But I get a Python Appcrash, after I give the parameter like: "15:23"
Problemsignatur: Problemereignisname: APPCRASH
Anwendungsname: python.exe Anwendungsversion: 0.0.0.0
Anwendungszeitstempel: 5194070d Fehlermodulname: QtCore4.dll
Fehlermodulversion: 4.8.4.0 Fehlermodulzeitstempel: 50eb4eec
Ausnahmecode: c0000005 Ausnahmeoffset: 0000000000033810
Betriebsystemversion: 6.2.9200.2.0.0.256.49 Gebietsschema-ID: 1031
Zusatzinformation 1: c436 Zusatzinformation
2: c436a4fc38414d2d1792ffc3e15f3c19 Zusatzinformation 3: 664a
Zusatzinformation 4: 664a8423adc2000b0b283f71335a059d
Reinstalled QT, Python and PySide, but nothing worked.
Any suggestions?
I borrowed this code from another StackOverflow answer:
from PyQt4 import QtCore
#QtCore.pyqtSlot(str)
def directory_changed(path):
print('Directory Changed!!!')
#QtCore.pyqtSlot(str)
def file_changed(path):
print('File Changed!!!')
fs_watcher = QtCore.QFileSystemWatcher(['/path/to/files_1', '/path/to/files_2', '/path/to/files_3'])
fs_watcher.connect(fs_watcher, QtCore.SIGNAL('directoryChanged(QString)'), directory_changed)
fs_watcher.connect(fs_watcher, QtCore.SIGNAL('fileChanged(QString)'), file_changed)
The problem is, file_changed never gets called, no matter what. directory_changed is reliably called when a file is added, for example, but changing the files content does not result in file_changed being called.
I called a few variations of QtCore.SIGNAL('fileChanged(QString)'), eg, QtCore.SIGNAL('fileChanged(const QString &)'), to no avail. There are no warnings, or errors -- it simply does not trigger the function.
Recommendations?
It's hard to be certain what's going wrong, because the example code is incomplete, and so cannot work at all as it stands.
However, assuming the real code you are running is more or less sane/complete, your problem is probably caused by not adding the directory itself to the list of paths.
A basic script should look something like this:
import sys
from PyQt4 import QtCore
def directory_changed(path):
print('Directory Changed: %s' % path)
def file_changed(path):
print('File Changed: %s' % path)
app = QtCore.QCoreApplication(sys.argv)
paths = [
'/path/to',
'/path/to/files_1',
'/path/to/files_2',
'/path/to/files_3',
]
fs_watcher = QtCore.QFileSystemWatcher(paths)
fs_watcher.directoryChanged.connect(directory_changed)
fs_watcher.fileChanged.connect(file_changed)
sys.exit(app.exec_())
import argparse
import configparser
import os
import sys
from PyQt5 import QtCore
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QDesktopWidget, QMessageBox
from PyQt5.QtWidgets import QMainWindow
from ProgressBar_ui import Ui_Form
class ProgressBarWindow(QMainWindow, Ui_Form):
def __init__(self):
super().__init__()
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.progressBar.setMinimum(0)
self.ui.progressBar.setMaximum(0)
self.ui.progressBar.setValue(0)
self.setWindowTitle("Progress Bar")
self.MSversion = ""
self.LOADING_LOG_PATH = ""
mainIco = ("Icons\myIcon.ico")
self.setWindowIcon(QIcon(mainIco))
self.ui.label.setText("")
self.ui.label.setWordWrap(True)
def location_on_the_screen(self):
ag = QDesktopWidget().availableGeometry()
sg = QDesktopWidget().screenGeometry()
widget = self.geometry()
x = ag.width() - widget.width()
y = 2 * ag.height() - sg.height() - widget.height()
self.move(x, y)
def file_changed(self, pathPassed):
if os.path.exists(pathPassed):
f = open(pathPassed, "r")
for x in f:
#print(x)
label =x
self.ui.label.setText(label)
if x == "CloseLoading":
self.close()
def main():
app = QApplication(sys.argv)
w = ProgressBarWindow()
w.setWindowFlags(w.windowFlags() & ~QtCore.Qt.WindowMaximizeButtonHint)
parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser(description='ProgressBar Arguments')
parser.add_argument('version', action="store", type=str)
args = vars(parser.parse_args())
if len(sys.argv) < 1:
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
errorMsg = "There are less than 2 command line arguments provided.\nLauncher can not be run."
msg.setText(errorMsg)
msg.setWindowTitle("Save paths..")
msg.exec_()
sys.exit()
p= '/path/toFile/'
paths = [ p ]
fs_watcher = QtCore.QFileSystemWatcher(paths)
#fs_watcher.directoryChanged.connect(w.directory_changed)
fs_watcher.fileChanged.connect(w.file_changed)
w.location_on_the_screen()
w.show()
app.exec_()
if __name__ == "__main__":
sys.exit(main())