AttributeError: 'QString' object has no attribute 'rfind'

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

My application runs fine in one computer but when I run the same application in another I get the error:

Traceback (most recent call last):   File "./th.py", line 98, in browse_file2     self.textEdit_2.append(str(os.path.basename(p)))   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 121, in basename     i = p.rfind('/') + 1 AttributeError: 'QString' object has no attribute 'rfind'

I have seen a similar error here. According to this, I need to typecast parameter to 'QString' datatype and I am doing that.The part of script that is having error is:

def browse_file(self):     #files handling       caption="Open File"     directory='./'     filter_mask="fastq files (*.fastq)"     self.textEdit.setText("")     f_1=(QFileDialog.getOpenFileNames(None, caption, directory, filter_mask))     #for st in f_1:     for p in f_1:      self.textEdit.append(str(os.path.basename(p)))     global R1     R1=f_1          #if textEdit.toPlainText   def browse_file2(self):     #files handling     caption="Open File"     directory='./'     filter_mask="fastq files (*.fastq)"     f_2=(QFileDialog.getOpenFileNames(None, caption, directory, filter_mask))     for p in f_2:      self.textEdit_2.append(str(os.path.basename(p)))      global R2      R2=f_2

Can someone please tell what may be the possible cause of this error? Let me know if you need any other part of code. Thanks in advance.

回答1:

When pyqt first wrapped Qt, they kept the QString class instead of casting it to native python strings (ie. str). Most python libraries that operate on strings (like os.path) expect str or unicode objects, not QString's. This means that you constantly have to type-cast all the return values from pyqt

text = unicode(mywidget.text())

Fortunately, pyqt has newer versions of the api that automatically do the type-casting for you. You just need to tell it to use the newer api. At the beginning of your python code, before you do any other imports, you can do this

import sip sip.setapi('QString', 2)

There are newer api's for a number of objects as well.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!