Pyqt5 and python3, what is the proper way to use functions from multiple classes

admin.unu Source

I started to learn pyqt5 and python3 a few months ago so my knowledge level is basic-intermediate, now i'm stuck with a problem and i require your experience. I want to know what is the proper way to import functions from other classes or better said a proper way to use them. I won't paste the entire code just some demo code.

I have my main app code:

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        file_path = os.path.abspath('ui/optim_cont.ui')
        uic.loadUi(file_path, self)
        self.move(QtWidgets.QApplication.desktop().screen().rect().center() - self.rect().center())
        self.menubar.setNativeMenuBar(False)
        login_dialog.dbsignal.connect(self.start_database)

    def start_database(self, option):
        """Function starts database depending the option signal received from login"""

        data = SettingsClass().get_data_json()
        if option == 0:
            sql_db = DatabaseConnector(hostname=Cryptograph().decoding(data['database']['address']),
                                       dbname=data['database']['name'],
                                       username=None,
                                       password=None,
                                       port=None,
                                       dbtype="QSQLITE")
            sql_db.run()
        elif option == 1:
            sql_db = DatabaseConnector(hostname=Cryptograph().decoding(data['database']['address']),
                                       dbname=data['database']['name'],
                                       username=Cryptograph().decoding(data['database']['user']),
                                       password=Cryptograph().decoding(data['database']['parola']),
                                       port=Cryptograph().decoding(data['database']['port']),
                                       dbtype="QMYSQL")
            sql_db.run()
        if sql_db.check() is True:
            pass
        else:
            TrayIcon().messageCritical('DB Error', 'Nu functioneaza conexiunea DB')
            sql_db.stop()



if __name__ == '__main__':
    global settings_dialog, main_window, setting_class
    app = QtWidgets.QApplication(sys.argv)
    tray = TrayIcon()
    popup = PopMessage
    login_dialog = login.LoginScreen()
    login_dialog.show()
    if os.path.isfile("properties.json") is True:
        setting_class = SettingsClass()
        settings_dialog = SettingsScreen()
    main_window = MainWindow()
    sys.exit(app.exec_())

The code works like this: LoginScreen() shows, i input my credentials, they are aproved and then the login window sends a signal to MainWindow() starting the database using a function. DatabaseConnector() is located inside another file, called extensions.py.

extensions.py looks like this:

class DatabaseConnector():
    def __init__(self, hostname, dbname, username, password, port, dbtype ):
        self.hostname = hostname
        self.dbname = dbname
        self.username = username
        self.password = password
        self.port = port
        self.dbtype = dbtype
        if self.dbtype == "QSQLITE":
            self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
            self.db.setDatabaseName("{}.db".format(self.dbname))
            self.db.setHostName(self.hostname)
        elif self.dbtype == "QMYSQL":
            self.db = QtSql.QSqlDatabase.addDatabase("QMYSQL")
            self.db.setDatabaseName(self.dbname)
            self.db.setHostName(self.hostname)
            self.db.setUserName(self.username)
            self.db.setPassword(self.password)
            self.db.setPort(int(self.port))
        else:
            pass

    def run(self):
        self.db.open()

    def stop(self):
        self.db.close()
        if self.dbtype == "QSQLITE":
            self.db = QtSql.QSqlDatabase.removeDatabase("QSQLITE")
        elif self.dbtype == "QMYSQL":
            self.db = QtSql.QSqlDatabase.removeDatabase("QMYSQL")

    def check(self):
        """Return True if db connection is open"""
        if self.db.isOpen():
            return True
        else:
            return False

My problem is, if i want to run def run(self) from DatabaseConnector from the login window using this method connector = DatabaseConnector() then connector.check() i get an error because i need to input the arguments for that class. If i go by this method connector = DatabaseConnector then connector.check(self) i get an error stating object has no attribute db

So what is the best way to run def check(self) and get it's return without calling another instance of that class? In my case it would create another connection if i call this function again.

Thank you.

python-3.xpyqtpyqt5

Answers

comments powered by Disqus