Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow a background task to use the message bar #38

Open
Rikuoja opened this issue Jun 3, 2021 · 4 comments
Open

Allow a background task to use the message bar #38

Rikuoja opened this issue Jun 3, 2021 · 4 comments
Assignees

Comments

@Rikuoja
Copy link

Rikuoja commented Jun 3, 2021

Add support for bar_msg in setup_task_logger. Will make a PR on this.

@Rikuoja Rikuoja self-assigned this Jun 3, 2021
@Rikuoja
Copy link
Author

Rikuoja commented Jun 3, 2021

Probably not doable? Looks like message bar cannot be accessed from outside the main thread :(

@Rikuoja
Copy link
Author

Rikuoja commented Jun 3, 2021

@Joonalai
Copy link

Joonalai commented Jun 7, 2021

Background tasks can use feedback and the UI thread could use that feedback message to display messages on message bar 🤔

@ivanlonel
Copy link

This is how I got it working.

In the UI thread:

@staticmethod
def pop_widget(mbi: QgsMessageBarItem) -> None:
    if mbi in iface.messageBar().items():
        iface.messageBar().popWidget(mbi)

@classmethod
def prepare_task(cls, task: QgsTask, message: str, maximum: Optional[int] = None) -> None:
    msg_bar = iface.messageBar()
    mbi_progress = msg_bar.createMessage(message)

    progress_bar = QProgressBar(mbi_progress)
    progress_bar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
    if maximum is not None:
        progress_bar.setMaximum(maximum)
        task.progressChanged.connect(progress_bar.setValue)
    else:
        progress_bar.setRange(0, 0)
    mbi_progress.layout().addWidget(progress_bar)
    msg_bar.pushWidget(mbi_progress, Qgis.Info)

    btn_close: QToolButton = msg_bar.findChildren(QToolButton)[0]

    for slot in (
        functools.partial(cls.pop_widget, mbi_progress),
        functools.partial(btn_close.clicked.disconnect, task.cancel),
    ):
        task.taskCompleted.connect(slot)
        task.taskTerminated.connect(slot)

    btn_close.clicked.connect(task.cancel)
    QgsApplication.taskManager().addTask(task)

Then, in task's run method, keep updating progress with self.setProgress() and checking self.isCanceled() to see if the message bar's close button was clicked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants