简体   繁体   中英

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

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM