"RuntimeError: super-class __init__() of %S was never called" when using self.tr in __init__ call

StackOverflow https://stackoverflow.com/questions/21671932

  •  09-10-2022
  •  | 
  •  

Вопрос

In code over PyQt, when self.tr is used in call to init of the ancestor class, an error is produced. The call without self.tr works. See below:

import sys
from PyQt4 import QtGui

class cl1(QtGui.QWidget):
  def __init__(self,txt):
    super(cl1,self).__init__()
    self.edit = QtGui.QLineEdit(txt)
    lay = QtGui.QVBoxLayout()
    lay.addWidget(self.edit)
    self.setLayout(lay)
    self.show()

class cl2(cl1):
  def __init__(self):
    # This line does not work:
    super(cl2,self).__init__(self.tr("kuku"))
    # If this line is used instead, it works:
    # super(cl2,self).__init__("kuku")

app = QtGui.QApplication(sys.argv)
w = cl2()
sys.exit(app.exec_())
Это было полезно?

Решение

As has already been pointed out, you cannot call a method of a base-class before it has been initialized.

One way to work around this issue is to use the static QApplication.translate method (PyQt does not provide a static QObject.tr method):

    super(cl2,self).__init__(QtGui.QApplication.translate("cl2", "kuku"))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top