pyqt5 form and outer module exchange data

I have a Pyqt5 form where the user enters data. This data is sent to another module, where it is processed and returned for display in the form.

Very simplistically it looks like this:

frm.py

import sys
from PyQt5.QtWidgets import *
import mdl


def fnc0(in_val):
    mdl.fnc1(in_val)


def fnc2(rezult):
    msg.setText(rezult)


app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout()

btn = QPushButton('button')
btn.clicked.connect(lambda: fnc0(5))

layout.addWidget(btn)
msg = QLabel('')
layout.addWidget(msg)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())

mdl.py

import frm


def fnc1(in_val):
    out_val = str(in_val*2)
    frm.fnc2(out_val)

However, when doing this, I get the error of using circular modules:

AttributeError: partially initialized module 'mdl' has no attribute 'fnc1' (most likely due to a circular import)

Is it possible to process the data sent from the form to another module, and then return the result to the form?

Upvotes: 0

Views: 86

Answers (1)

eyllanesc
eyllanesc

Reputation: 244132

A possible solution is that in a third file we create a logic where we can register functions that receive the result and a function that invokes those functions:

core.py

_funct = []


def register_writer(func):
    _funct.append(func)
    return func

def write(text):
    for f in _funct:
        f(text)

mdl.py

import core


def fnc1(in_val):
    out_val = str(in_val * 2)
    core.write(out_val)

frm.py

import sys
from PyQt5.QtWidgets import *

import core
import mdl


@core.register_writer
def fnc2(rezult):
    msg.setText(rezult)


app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout()

btn = QPushButton("button")
btn.clicked.connect(lambda: mdl.fnc1(5))

layout.addWidget(btn)
msg = QLabel()
layout.addWidget(msg)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())

Upvotes: 2

Related Questions