Aadit
Aadit

Reputation: 199

How to restore resource.qrc file from resources_rc.py

As I am facing data loss, I have a corrupted resource.qrc file when I tried recovering it and I also lost my graphics files (.png, .jpg) - but my Qt application is running fine.

The problem is when I need to edit the .ui files, I have a corrupted resource.qrc file. My resources_rc.py file is all well, which I created by the following command:

pyrcc4 -o resource.py resource.qrc

So is there any way I can get my resource.qrc back from the resources_rc.py file?

Upvotes: 1

Views: 4206

Answers (1)

ekhumoro
ekhumoro

Reputation: 120638

The script below will reconstruct a qrc file and all the original resources from a resources_rc.py file generated by pyrcc. It will work with PyQt4/5 and Python 2/3. The files will be written to a temporary directory in the same directory as the given resources_rc.py file.

Usage:

python qrc_gen.py path/to/resources_rc.py

qrc_gen.py:

import sys, os, tempfile
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore
# from PyQt5 import QtCore

respath = os.path.abspath(sys.argv[1])
dirpath = os.path.dirname(respath)
sys.path.insert(0, dirpath)

import resources_rc

tmpdir = tempfile.mkdtemp(prefix='qrc_', dir=dirpath)

it = QtCore.QDirIterator(':', QtCore.QDirIterator.Subdirectories)

files = []

while it.hasNext():
    uri = it.next()
    path = uri.lstrip(':/')
    if path.startswith('qt-project.org'):
        continue
    tmp = os.path.join(tmpdir, path)
    if it.fileInfo().isDir():
        try:
            os.makedirs(tmp)
        except OSError:
            pass
    else:
        res = QtCore.QFile(uri)
        res.open(QtCore.QIODevice.ReadOnly)
        with open(tmp, 'wb') as stream:
            stream.write(bytes(res.readAll()))
        res.close()
        files.append('    <file>%s</file>\n' % path.lstrip(':/'))

with open(os.path.join(tmpdir, 'resources.qrc'), 'w') as stream:
    stream.write('<!DOCTYPE RCC><RCC version="1.0">\n')
    stream.write('<qresource>\n%s</qresource>\n' % ''.join(files))

Upvotes: 1

Related Questions