PyQt and Qt Designer - pyqt5

This is a minor problem but it irritates me
I use PyQt
I use Qt Designer
I use PyUic5 to generate the Ui_MyDialog from the output of the Qt designer
I created a custom widget and a plugin and managed to operate an insertion
of my custom widget to a dialog
I managed to operate the dialog and see my custom widget in action.
The problem is that in the Ui_MyDialog.py that is generated by the PyUic5 there
is (at the end of the file) an import for my custom widget and the file name of my custom widget is in lowercase letters and not the way the file is
I looked in the plugin and there is no place where such a filename is declared
What can be the problem?
I gave here the whole file. The problem is in the last line
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Ui\PlotDialog.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_PlotDialog(object):
def setupUi(self, PlotDialog):
PlotDialog.setObjectName("PlotDialog")
PlotDialog.resize(400, 300)
self.horizontalLayout = QtWidgets.QHBoxLayout(PlotDialog)
self.horizontalLayout.setObjectName("horizontalLayout")
self.myQtPlotContainer = MyQtPlotConteiner(PlotDialog)
self.myQtPlotContainer.setObjectName("myQtPlotContainer")
self.horizontalLayout.addWidget(self.myQtPlotContainer)
self.buttonBox = QtWidgets.QDialogButtonBox(PlotDialog)
self.buttonBox.setOrientation(QtCore.Qt.Vertical)
self.buttonBox.setStandardButtons (QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.horizontalLayout.addWidget(self.buttonBox)
self.retranslateUi(PlotDialog)
self.buttonBox.accepted.connect(PlotDialog.accept)
self.buttonBox.rejected.connect(PlotDialog.reject)
QtCore.QMetaObject.connectSlotsByName(PlotDialog)
def retranslateUi(self, PlotDialog):
_translate = QtCore.QCoreApplication.translate
PlotDialog.setWindowTitle(_translate("PlotDialog", "Dialog"))
self.myQtPlotContainer.setToolTip(_translate("PlotDialog", "The current time"))
self.myQtPlotContainer.setWhatsThis(_translate("PlotDialog", "The analog clock widget displays the current time."))
from myqtplotconteiner import MyQtPlotConteiner

Related

QWebEngineView crashes when loading a PDF

I am porting my small project from pyqt5 to pyqt6 which deals with displaying PDFs using QWebEngineView.
I used this PyQt5 snippet to display the PDF below:
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings
class Window(QWidget):
def __init__(self):
super().__init__()
self.webView = QWebEngineView()
self.webView.settings().setAttribute(QWebEngineSettings.PluginsEnabled, True)
self.webView.settings().setAttribute(QWebEngineSettings.PdfViewerEnabled, True)
url = QUrl.fromLocalFile(r"C:/Users/Eliaz/Desktop/qt5cadaquesPart14.pdf")
self.webView.setUrl(url)
self.webView.show()
app = QApplication(sys.argv)
ex = Window()
sys.exit(app.exec())
Now when I ported it into a PyQt6 snippet given in the code below, the program is just crashing without any error messages:
import sys
from PyQt6.QtGui import *
from PyQt6.QtCore import *
from PyQt6.QtWidgets import *
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtWebEngineCore import QWebEngineSettings
class Window(QWidget):
def __init__(self):
super().__init__()
self.webView = QWebEngineView()
self.webView.settings().setAttribute(QWebEngineSettings.WebAttribute.PluginsEnabled, True)
self.webView.settings().setAttribute(QWebEngineSettings.WebAttribute.PdfViewerEnabled, True)
url = QUrl.fromLocalFile(r"C:/Users/Eliaz/Desktop/qt5cadaquesPart14.pdf")
self.webView.setUrl(url)
self.webView.show()
app = QApplication(sys.argv)
ex = Window()
sys.exit(app.exec())
Before exiting though, it shows these information on the console:
qt.webenginecontext:
GL Type: desktop
Surface Type: OpenGL
Surface Profile: CompatibilityProfile
Surface Version: 4.6
QSG RHI Backend: OpenGL
Using Supported QSG Backend: yes
Using Software Dynamic GL: no
Using Multithreaded OpenGL: yes
Init Parameters:
* application-name python
* browser-subprocess-path C:\Users\Eliaz\AppData\Local\Programs\Python\Python310\lib\site-packages\PyQt6\Qt6\bin\QtWebEngineProcess.exe
* create-default-gl-context
* disable-es3-gl-context
* disable-features ConsolidatedMovementXY,InstalledApp,BackgroundFetch,WebOTP,WebPayments,WebUSB,PictureInPicture
* disable-speech-api
* enable-features NetworkServiceInProcess,TracingServiceInProcess
* enable-threaded-compositing
* in-process-gpu
* use-gl desktop
Even with the additional information above, I can't still find what's wrong with my code but I'm certain that the path of the PDFs exists.
Also, I am on Windows 10 These are the versions of PyQt6 that I have. (Updated)
PyQt6 6.3.1
PyQt6-Qt6 6.3.1
PyQt6-sip 13.4.0
PyQt6-WebEngine 6.3.1
PyQt6-WebEngine-Qt6 6.3.1
Update:
I tried updating the pyqt6 packages installed in my system to 6.3.1, and testing it in a fresh virtual box but it still crashes as seen in this GIF.
This seems to be caused by a Windows-specific bug, since eveything works as expected on Linux using both PyQt-5.15.7 and PyQt-6.1.3. It's hard to say what the cause might be, given that there's no relevant output.
As a work-around, an alternative is to use PDF.js. See here for more details:
How to render PDF using pdf.js viewer in PyQt?
But note that it may be necessary to use the legacy version with PyQt5.

Getting the error in python selenium testing for login and logout functionality

I am getting the error as...
AttributeError: 'LoginTestCase' object has no attribute 'driver'
And the code is
from selenium import webdriver;
from selenium.webdriver.common.keys import Keys
import time
import unittest
class LoginTest(unittest.TestCase):
#classmethod
def setUpclass(cls):
cls.driver = webdriver.Firefox("D:/Frontend/18-01-2021/selenium-testing")
cls.driver.implicitly_wait(10)
cls.driver.maximize_window()
def test_login_valid(self):
self.driver.get("http://localhost:4200")
self.driver.find_element_by_name("username").send_keys("admin")
self.driver.find_element_by_name("password").send_keys("admin#123")
self.driver.find_element_by_id('log').click()
self.driver.find_element_by_id('ab').click()
self.driver.find_element_by_id('usersinfo').click()
self.driver.find_element_by_id('log_out').click()
time.sleep(8)
#classmethod
def tearDownClass(cls):
cls.driver.close()
cls.driver.quit()
print("Test Completed")
I have built the above code for testing login to functionality using selenium with python unit testing .
But while executing the python code showing some errors as
AttributeError: 'LoginTestCase' object has no attribute 'driver'
Can anyone help me regarding this
There are some typos in your code:
setUpclass should be setUpClass
the test method is not indented correctly.
I think that fixing the setUpClass typo will get you going.

Is there a way to run code after reactor.run() in scrapy?

I am working on a scrapy api. One of my issues was that the twisted reactor wasn't restartable. I fixed this using crawl runner as opposed to crawl process. My spider extracts links from a website, validates them. My issue is that if I add the validation code after reactor.run() it doesn't work. This is my code:
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from twisted.internet import reactor
from urllib.parse import urlparse
list = set([])
list_validate = set([])
runner = CrawlerRunner()
class Crawler(CrawlSpider):
name = "Crawler"
start_urls = ['https:www.example.com']
allowed_domains = ['www.example.com']
rules = [Rule(LinkExtractor(), callback='parse_links', follow=True)]
configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s'})
def parse_links(self, response):
base_url = url
href = response.xpath('//a/#href').getall()
list.add(urllib.parse.quote(response.url, safe=':/'))
for link in href:
if base_url not in link:
list.add(urllib.parse.quote(response.urljoin(link), safe=':/'))
for link in list:
if base_url in link:
list_validate.add(link)
runner.crawl(Crawler)
reactor.run()
If add the code that validates the links after reactor.run(), it doesn't get executed. And if I put the code before reactor.run(), nothing happens because the spider hasn't yet finished crawling all the links. What should I do? The code that validates the links is perfectly fine I used it before and it works.
We can do that with d.addCallback(<callback_function>) and d.addErrback(<errback_function>)
...
runner = CrawlerRunner()
d = runner.crawl(MySpider)
def finished(d):
print("finished :D")
def spider_error(err):
print("Spider error :/")
d.addCallback(finished)
d.addErrback(spider_error)
reactor.run()
For your ScraperApi you can use Klein.
Klein is a micro-framework for developing production-ready web services with Python. It is 'micro' in that it has an incredibly small API similar to Bottle and Flask.
...
import scrapy
from scrapy.crawler import CrawlerRunner
from klein import Klein
app=Klein()
#app.route('/')
async def hello(request):
status=list()
class TestSpider(scrapy.Spider):
name='test'
start_urls=[
'https://quotes.toscrape.com/',
'https://quotes.toscrape.com/page/2/',
'https://quotes.toscrape.com/page/3/',
'https://quotes.toscrape.com/page/4/'
]
def parse(self,response):
"""
parse
"""
status.append(response.status)
runner=CrawlerRunner()
d= await runner.crawl(TestSpider)
content=str(status)
return content
#app.route('/h')
def index(request):
return 'Index Page'
app.run('localhost',8080)

scrapy not entering parse(response.url)

I'm a beginner. When I crawl, there is no error code, but scrapy does not enter response.url in parse. That is, the page is empty page titled "data;"
how to enter the repsonse.url?
import scrapy
from selenium import webdriver
from scrapy.selector import Selector
import time
from result_crawler.items import RESULT_Item
class RESULT_Spider(scrapy.Spider):
name="EPL"
allowed_domains=["premierleague.com"]
starts_urls=["https://www.premierleague.com/match/38567"]
def __init__(self):
scrapy.Spider.__init__(self)
self.browser=webdriver.Chrome("/users/germpark/chromedriver")
def parse(self,response):
self.browser.get(response.url)
time.sleep(5)
.
.
.
I want to enter https://www.premierleague.com/match/38567 but result did not exist.
The correct property name is start_urls not starts_urls. Because of the incorrect property name it does not detect any start pages.

How debuging twisted application in PyCharm

I would like to debug a Twisted Application in PyCharm
from twisted.internet import defer
from twisted.application import service, internet
from txjason.netstring import JSONRPCServerFactory
from txjason import handler
class Example(handler.Handler):
def __init__(self, who):
self.who = who
#handler.exportRPC("add")
#defer.inlineCallbacks
def _add(self, x, y):
yield
defer.returnValue(x+y)
#handler.exportRPC()
def whoami(self):
return self.who
factory = JSONRPCServerFactory()
factory.addHandler(Example('foo'), namespace='bar')
application = service.Application("Example JSON-RPC Server")
jsonrpcServer = internet.TCPServer(7080, factory)
jsonrpcServer.setServiceParent(application)
How to run app from command line I know, but how to start debugging in PyCharm can't understand
Create a new Run Configuration in PyCharm, under the "Python" section.
If you start this application using twistd, then configure the "Script" setting to point to that twistd, and the "script parameters" as you would have them on the command line. You'll probably want to include the --nodaemon option.
You should then be able to Run that under PyCharm, or set breakpoints and Debug it.