Python macro: Update cell contents during execution

Hi. I have a problem, similar to this question (The provided answer does not work for me). I have a python macro in a Calc document that runs a long calculation and I would like to update cell contents during the macro’s execution. Here is a simple example:

import time

def myfunction(*args):
    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    sheet = model.CurrentController.ActiveSheet

    cell = sheet.getCellByPosition(0, 0)
    cell.setString("In progress...")

    # Some long calculation
    time.sleep(5)

    cell = sheet.getCellByPosition(1, 0)
    cell.setString("done.")

    return None

My problem is that “In progress” is not displayed until the function returns, when “In progress…” and “done.” appear at once. Is there a way to update cell contents during the execution of the macro?

I have attached a document with the macro included.

Hello,

You can cure this by branching off the calculation and finishing string with a thread. Code in sample:

import time
from threading import Thread

def myfunction(*args):
    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    sheet = model.CurrentController.ActiveSheet
    cell = sheet.getCellByPosition(0, 0)
    cell.setString("In progress...")
    t1 = Thread(target=setSelected)
    t1.start()
    return None

def setSelected():
    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    sheet = model.CurrentController.ActiveSheet
    # Some long calculation
    time.sleep(25)
    cell = sheet.getCellByPosition(1, 0)
    cell.setString("done.")

Attached is a sample with the code. Have added a push button to start the macro and increased the sleep time to 25 to more easily see the effects and be able to modify existing cells while the macro is running.

Sample ---- CalcThreading.ods