Ask Your Question
0

Python macro: Update cell contents during execution

asked 2018-09-28 15:32:11 +0200

sgerber gravatar image

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.

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
0

answered 2018-09-28 17:15:23 +0200

Ratslinger gravatar image

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

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2018-09-28 15:32:11 +0200

Seen: 131 times

Last updated: Sep 28 '18