在QIODevice子类中重写readData返回错误结果

1 投票
3 回答
1397 浏览
提问于 2025-04-17 09:09

我正在尝试在PySide中对QFile进行子类化,以实现自定义的读取行为。不过,如下面简化的代码所示,即使子类的readData实现只是调用了父类的readData函数,返回的数据还是不正确。对其他QIODevices,比如QBuffer进行子类化也会导致返回值不正确。有没有人成功地对子类化QIODevice呢?

from PySide import QtCore

class FileChild1(QtCore.QFile):
    pass

class FileChild2(QtCore.QFile):
    def readData(self, maxlen):
        return super(FileChild2, self).readData(maxlen)


f1 = FileChild1('test.txt')
f1.open(QtCore.QIODevice.ReadWrite|QtCore.QIODevice.Truncate)
f1.write('Test text for testing')
f1.seek(0)
print 'FileChild1: ', repr(f1.read(50))

f2 = FileChild2('test2.txt')
f2.open(QtCore.QIODevice.ReadWrite|QtCore.QIODevice.Truncate)
f2.write('Test text for testing')
f2.seek(0)
print 'FileChild2: ', repr(f2.read(50))

>>> FileChild1:  PySide.QtCore.QByteArray('Test text for testing')
>>> FileChild2:  PySide.QtCore.QByteArray('─ Q ►│A☻ @  p¼a☻Test text for testing\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

3 个回答

0

在Qt5和PySide2上也是非常有效的。我们正在进行调查。

1

PySide中的这个问题源自shiboken,具体来说就是:在QIODevice中,qint64被用作偏移量类型,但在Python 2.x中,qint64被映射成了“int”,而不是“long”。当qint64的值大于qint32时,读取这个值会导致Python 2.x抛出OverflowError(溢出错误)。

当使用qint64作为槽、信号、属性或其他Qt元类型来在Qt C++代码和Python之间进行通信时,也会出现类似的OverflowError。

我也在寻找解决这个问题的方法。

2

我用Python 2.7.2和Qt 4.8.0测试了你的脚本,分别在PyQt 4.8和PyQt 4.9上,结果都是这样:

FileChild1:  'Test text for testing'
FileChild2:  'Test text for testing'

所以,readData返回的是一个字节字符串,这个可以在PyQt4的文档里找到。

然后我用Python 2.7.2和Qt 4.8.0测试了PySide 1.0.9,结果是这样的:

FileChild1:  PySide.QtCore.QByteArray('Test text for testing')
FileChild2:  PySide.QtCore.QByteArray('')

我不太明白为什么PyQt4和PySide的返回类型会不一样,但显然PySide里有某种bug。

这里有一个bug报告在这里,看起来可能和这个问题有点关系,不过这个报告不是特别新(是关于PySide 1.0.7的)。

撰写回答