简体   繁体   中英

Using external class methods inside the imported module

My python application consists of various separate processing algorithms/modules combined within a single (Py)Qt GUI for ease of access.

Every processing algorithm sits within its own module and all the communication with GUI elements is implemented within a single class in the main module. In particular, this GUI class has a progressbar ( QProgressBar ) object designed to represent the current processing progress of a chosen algorithm. This object has .setValue() method ( self.dlg.progressBar.setValue(int) ).

The problem is that since self.dlg.progressBar.setValue() is a class method I cannot use it inside my imported processing modules to report their progress state within their own code .

The only workaround I found is to add progressbar variable to definition of each processing module, pass there self.dlg.progressBar inside the main module and then blindly call progressbar.setValue(%some_processing_var%) inside the processing module.

Is this the only way to use outer class methods inside imported modules or are there better ways?

No. I think this approach somewhat breaks software engineering principles (eg single responsibility ). In single responsibility principle, each module is only in charge of its assigned task and nothing else. If we consider UI a separate layer, so your processing modules shouldn't have anything to do with the UI layer.

In this case, your modules should have a method called publish_progress(callback) which callback is a function to be called for each progress step ( more info ). Then, in your UI layer define a function which is given an integer (between 0 to 100) and updates the progress bar. Once you've defined it, you should register it with publish_progress method of your modules.

def progress_callback(prg):
    self.dlg.progressBar.setValue(prg)

Registering it:

my_module.publish_progress(progress_callback)

Calling the callback in your module:

progress_callback(0)
...
# do something
...
progress_callback(20)
...
# do something
...
progress_callback(100)

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