-1

I have two scripts files which are test_qt.py and test.py. I want to call a function when I press the push button. But this function it is not inside the Widget file(test_qt). I can call the function easily if it is inside the Widget file but if i try to call it out of the test_qt, I get this error "AttributeError: 'Ui_Form' object has no attribute 'test_something'". I have checked many examples but I havent solved yet. I want to call test_something() function. I dont know where is the mistake. I defined print_something() function to call the test_something()

#----test_qt.py----
from PyQt5 import QtCore, QtGui, QtWidgets
from test import*

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(150, 100, 93, 28))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.print_something)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "PushButton"))

    def print_something(self):
        #strong textprint("click")
        self.test_something()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
---------------------------
#---- test.py -------------
def test_something():
    print("clicked")
---------------------------
Nobody
  • 79
  • 13
  • 1
    `test_something` is not an *attribute* of [**`self`**](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self-in-python). If you do `from test import *` in your `test_qt.py`, anything (publicly) declared in `test.py` (the `test` module) is considered a *`global`* *within* the `test_qt.py` script scope; just call `test_something()` and it'll work. – musicamante Dec 19 '19 at 04:00

1 Answers1

1

Removing the self in self.test_something() should call the imported function.

Note: Star imports are seen as code smell and can pollute the namespace or even worse overwrite existing symbols. You should try to avoid them :)

jerch
  • 682
  • 4
  • 9