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

3

I'm doing a small application in Pyqt4 to understand the operation. In a given part, I'm using a callback function to display a QLabel text that is typed in QtextEdit .

This text should be trimmed (remove spaces before and after the string).

When I tried to use the strip function present in str of Python the following error occurred:

  

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

As I understand, in PyQt, the string is not an object str , but QString and QString does not have the strip method.

In this case, what can I do to get my treated string?

Code:

def onButtonOkClicked(self):

    def setText():
        text = self.line.toPlainText().strip();
        self.label.setText(text)

    QtCore.QObject.connect(self.buttonOk, QtCore.SIGNAL("clicked()"), setText)
    
asked by anonymous 14.10.2016 / 19:28

3 answers

6

I'm just responding to one thing:

strip is a method for Python strings, QString is different from string , summarizing it is a QT object and will not have access to the same methods used in native python strings.

You will have to use the methods of QString as per the link documentation.

In the case as quoted in the other answers, use trimmed :

self.line.toPlainText().trimmed();
    
14.10.2016 / 19:47
5

You can use simplified() of QString itself. It is a more limited method, but it can work. Depending on what you want it can be used as well trimmed() too.

You can use replace(QString(" "), QString("")) if you want other characters.

Although I suggest avoiding it, you can also convert it to the string of Python:

str(text)

The two encodings are completely different, if you convert from one to another all the time you will waste resources. When using Qt the idea is to stay as much as possible with it and only convert when it is strictly necessary.

    
14.10.2016 / 19:39
3

The class QString has the function trimmed() , which returns a new QString with the whitespace removed from the beginning and end of the text.

Pyhton version documentation: link

C ++ version documentation: link

    
14.10.2016 / 19:40