"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