How can I read a resource file (say like assets/font-awesome/fonts/fontawesome-webfont.ttf or assets/jquery/js/jquery-1.11.0.min.js which declared in a myresources.qrc file and using pyrcc5.exe compiled to a myresources.py module) in to a byte array, byte string (b'') and string ('')?

I have successfully managed to implement a custom schema handler (to handle requests like myscheme://controller/action/?param1=100 , deriving classes from QNetworkAccessManager and QNetworkReply). I needed this for if later this app should go online, I would experience a (more) seamless migration process.

Now I need to serve the files in the resources (html, css, js, images, fonts, ...) to QWebView in my custom scheme. I've tried QFile and it's readAll method.

This is my code:

f = QFile('qrc:///assets/jquery/js/jquery-1.11.0.min.js')
f.open(QIODevice.ReadOnly | QIODevice.Unbuffered)

try:
    self.content = f.readAll()
finally:
    f.close()

It seems f.readAll() does nothing.

有帮助吗?

解决方案

Your resource path is not correct, and the exception handler is redundant, because an error won't be raised if the open/read fails (that's not a bug or misfeature - Qt just works differently to Python).

Try something like this, instead:

    stream = QFile(':/assets/jquery/js/jquery-1.11.0.min.js')
    if stream.open(QFile.ReadOnly):
        js = str(stream.readAll(), 'utf-8')
        stream.close()
    else:
        print(stream.errorString())
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top