KJob Class
The base class for all jobs. More...
Header: | #include <KJob> |
CMake: | find_package(KF6 REQUIRED COMPONENTS CoreAddons) target_link_libraries(mytarget PRIVATE KF6::CoreAddons) |
Inherits: | QObject |
Inherited By: |
Public Types
flags | Capabilities |
enum | Capability { NoCapabilities, Killable, Suspendable } |
enum | KillVerbosity { Quietly, EmitResult } |
enum | Unit { Bytes, Files, Directories, Items, UnitsCount } |
Properties
|
Public Functions
KJob(QObject *parent = nullptr) | |
KJob::Capabilities | capabilities() const |
(since 6.8) qint64 | elapsedTime() const |
int | error() const |
virtual QString | errorString() const |
QString | errorText() const |
bool | exec() |
bool | isAutoDelete() const |
(since 5.92) bool | isFinishedNotificationHidden() const |
(since 5.95) bool | isStartedWithExec() const |
bool | isSuspended() const |
unsigned long | percent() const |
qulonglong | processedAmount(KJob::Unit unit) const |
void | setAutoDelete(bool autodelete) |
(since 5.92) void | setFinishedNotificationHidden(bool hide = true) |
void | setUiDelegate(KJobUiDelegate *delegate) |
virtual void | start() = 0 |
qulonglong | totalAmount(KJob::Unit unit) const |
KJobUiDelegate * | uiDelegate() const |
Public Slots
Signals
void | description(KJob *job, const QString &title, const QPair<QString, QString> &field1 = QPair<QString, QString>(), const QPair<QString, QString> &field2 = QPair<QString, QString>()) |
void | infoMessage(KJob *job, const QString &message) |
void | percentChanged(KJob *job, unsigned long percent) |
void | processedSize(KJob *job, qulonglong size) |
void | result(KJob *job) |
void | speed(KJob *job, unsigned long speed) |
void | totalSize(KJob *job, qulonglong size) |
void | warning(KJob *job, const QString &message) |
Protected Functions
virtual bool | doKill() |
virtual bool | doResume() |
virtual bool | doSuspend() |
void | emitPercent(qulonglong processedAmount, qulonglong totalAmount) |
void | emitResult() |
void | emitSpeed(unsigned long speed) |
void | setCapabilities(KJob::Capabilities capabilities) |
void | setError(int errorCode) |
void | setErrorText(const QString &errorText) |
void | setPercent(unsigned long percentage) |
void | setProcessedAmount(KJob::Unit unit, qulonglong amount) |
(since 5.76) void | setProgressUnit(KJob::Unit unit) |
void | setTotalAmount(KJob::Unit unit, qulonglong amount) |
(since 6.8) void | startElapsedTimer() |
Detailed Description
For all jobs created in an application, the code looks like
void SomeClass::methodWithAsynchronousJobCall() { KJob *job = someoperation(some parameters); connect(job, &KJob::result, this, &SomeClass::handleResult); job->start(); }
(other connects, specific to the job)
And handleResult is usually at least:
void SomeClass::handleResult(KJob *job) { if (job->error()) { doSomething(); } }
With the synchronous interface the code looks like
void SomeClass::methodWithSynchronousJobCall() { KJob *job = someoperation( some parameters ); if (!job->exec()) { // An error occurred } else { // Do something } }
Subclasses must implement start(), which should trigger the execution of the job (although the work should be done asynchronously). errorString() should also be reimplemented by any subclasses that introduce new error codes.
Note: KJob and its subclasses are meant to be used in a fire-and-forget way. Jobs will delete themselves when they finish using deleteLater() (although this behaviour can be changed), so a job instance will disappear after the next event loop run.
Member Type Documentation
enum KJob::Capability
flags KJob::Capabilities
Constant | Value | Description |
---|---|---|
KJob::NoCapabilities | 0x0000 | None of the capabilities exist |
KJob::Killable | 0x0001 | The job can be killed |
KJob::Suspendable | 0x0002 | The job can be suspended |
The Capabilities type is a typedef for QFlags<Capability>. It stores an OR combination of Capability values.
enum KJob::KillVerbosity
Constant | Value |
---|---|
KJob::Quietly | 0 |
KJob::EmitResult | 1 |
enum KJob::Unit
Describes the unit used in the methods that handle reporting the job progress info.
Constant | Value | Description |
---|---|---|
KJob::Bytes | 0 | Directory and file sizes in bytes |
KJob::Files | 1 | The number of files handled by the job |
KJob::Directories | 2 | The number of directories handled by the job |
KJob::Items (since Qt 5.72) | 3 | The number of items (e.g. both directories and files) handled by the job |
KJob::UnitsCount (since Qt 5.87) | 4 | Used internally only, do not use |
See also totalAmount.
Property Documentation
[read-only]
capabilities : const Capabilities
Access functions:
KJob::Capabilities | capabilities() const |
[read-only]
error : const int
Access functions:
int | error() const |
Notifier signal:
void | result(KJob *job) | [see note below] |
Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.
[read-only]
errorString : const QString
Access functions:
virtual QString | errorString() const |
Notifier signal:
void | result(KJob *job) | [see note below] |
Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.
[read-only]
errorText : const QString
Access functions:
QString | errorText() const |
Notifier signal:
void | result(KJob *job) | [see note below] |
Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.
[read-only]
percent : const ulong
Access functions:
unsigned long | percent() const |
Notifier signal:
void | percentChanged(KJob *job, unsigned long percent) | [see note below] |
Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.
Member Function Documentation
[explicit]
KJob::KJob(QObject *parent = nullptr)
Creates a new KJob object.
parent the parent QObject
KJob::Capabilities KJob::capabilities() const
Returns the capabilities that this job supports
Note: Getter function for property capabilities.
See also setCapabilities().
[signal]
void KJob::description(KJob *job, const QString &title, const QPair<QString, QString> &field1 = QPair<QString, QString>(), const QPair<QString, QString> &field2 = QPair<QString, QString>())
Emitted to display general description of this job. A description has a title and two optional fields which can be used to complete the description.
Examples of titles are "Copying", "Creating resource", etc. The fields of the description can be "Source" with an URL, and, "Destination" with an URL for a "Copying" description.
job the job that emitted this signal
title the general description of the job
field1 first field (localized name and value)
field2 second field (localized name and value)
[virtual protected]
bool KJob::doKill()
Aborts this job quietly.
This simply kills the job, no error reporting or job deletion should be involved.
Returns true
if the operation is supported and succeeded, false
otherwise
[virtual protected]
bool KJob::doResume()
Resumes this job.
Returns true
if the operation is supported and succeeded, false
otherwise
[virtual protected]
bool KJob::doSuspend()
Suspends this job.
Returns true
if the operation is supported and succeeded, false
otherwise
[since 6.8]
qint64 KJob::elapsedTime() const
The number of milliseconds the job has been running for. Starting from the last start() call.
Sub-classes must call startElapsedTimer() from their start() implementation, to get elapsedTime() measurement. Otherwise this method will always return 0.
The time when paused is excluded.
This function was introduced in 6.8.
[protected]
void KJob::emitPercent(qulonglong processedAmount, qulonglong totalAmount)
Utility function for inherited jobs. Emits the percent signal if bigger than previous value, after calculating it from the parameters.
processedAmount the processed amount
totalAmount the total amount
See also percent().
[protected]
void KJob::emitResult()
Utility function to emit the result signal, and end this job. It first notifies the observers to hide the progress for this job using the finished() signal.
Note: Deletes this job using deleteLater().
See also result() and finished().
[protected]
void KJob::emitSpeed(unsigned long speed)
Utility function for inherited jobs. Emits the speed signal and starts the timer for removing that info
speed the speed in bytes/s
int KJob::error() const
Returns the error code, if there has been an error.
Only call this method from the slot connected to result().
Returns the error code for this job, 0 if no error.
Note: Getter function for property error.
See also setError().
[virtual]
QString KJob::errorString() const
A human-readable error message.
This provides a translated, human-readable description of the error. Only call if error is not 0.
Subclasses should implement this to create a translated error message from the error code and error text. For example:
if (error() == ReadFailed) { i18n("Could not read \"%1\"", errorText()); }
Returns a translated error message, providing error() is not 0
Note: Getter function for property errorString.
QString KJob::errorText() const
Returns the error text if there has been an error.
Only call if error is not 0.
This is usually some extra data associated with the error, such as a URL. Use errorString() to get a human-readable, translated message.
Returns a string to help understand the error
Note: Getter function for property errorText.
See also setErrorText().
bool KJob::exec()
Executes the job synchronously.
This will start a nested QEventLoop internally. Nested event loop can be dangerous and can have unintended side effects, you should avoid calling exec() whenever you can and use the asynchronous interface of KJob instead.
Should you indeed call this method, you need to make sure that all callers are reentrant, so that events delivered by the inner event loop don't cause non-reentrant functions to be called, which usually wreaks havoc.
Note that the event loop started by this method does not process user input events, which means your user interface will effectively be blocked. Other events like paint or network events are still being processed. The advantage of not processing user input events is that the chance of accidental reentrance is greatly reduced. Still you should avoid calling this function.
Returns true
if the job has been executed without error, false
otherwise
[signal]
void KJob::infoMessage(KJob *job, const QString &message)
Emitted to display state information about this job. Examples of message are "Resolving host", "Connecting to host...", etc.
job the job that emitted this signal
message the info message
bool KJob::isAutoDelete() const
Returns whether this job automatically deletes itself once the job is finished.
[since 5.92]
bool KJob::isFinishedNotificationHidden() const
Whether to not show a finished notification when a job's finished signal is emitted.
This function was introduced in 5.92.
See also setFinishedNotificationHidden().
[since 5.95]
bool KJob::isStartedWithExec() const
Returns true
if this job was started with exec(), which starts a nested event-loop (with QEventLoop::ExcludeUserInputEvents, which blocks the GUI), otherwise returns false
which indicates this job was started asynchronously with start().
This is useful for code that for example shows a dialog to ask the user a question, and that would be no-op since the user cannot interact with the dialog.
This function was introduced in 5.95.
bool KJob::isSuspended() const
Returns if the job was suspended with the suspend() call.
See also suspend() and resume().
[slot]
bool KJob::kill(KJob::KillVerbosity verbosity = KJob::Quietly)
Aborts this job.
This kills and deletes the job.
verbosity if equals to EmitResult, Job will emit signal result and ask uiserver to close the progress window.
verbosity is set to EmitResult for subjobs. Whether applications should call with Quietly or EmitResult depends on whether they rely on result being emitted or not. Please notice that if verbosity is set to Quietly, signal result will NOT be emitted.
Returns true
if the operation is supported and succeeded, false otherwise
unsigned long KJob::percent() const
Returns the overall progress of this job
Note: Getter function for property percent.
See also setPercent().
qulonglong KJob::processedAmount(KJob::Unit unit) const
Returns the processed amount of a given unit for this job.
unit the unit of the requested amount
See also setProcessedAmount().
[signal]
void KJob::processedSize(KJob *job, qulonglong size)
Regularly emitted to show the progress of this job (current data size in bytes for transfers, entries listed, etc.).
Note: This is a private signal, it shouldn't be emitted directly by subclasses of KJob, use setProcessedAmount() instead.
job the job that emitted this signal
size the processed size
[slot]
bool KJob::resume()
Resumes this job.
Returns true
if the operation is supported and succeeded, false
otherwise
void KJob::setAutoDelete(bool autodelete)
Sets the auto-delete property of the job. If autodelete is set to false
the job will not delete itself once it is finished.
The default for any KJob is to automatically delete itself, which implies that the job was created on the heap (using new). If the job is created on the stack (which isn't the typical use-case for a job) then you must set auto-delete to false
, otherwise you could get a crash when the job finishes and tries to delete itself.
Note: If you set auto-delete to false
then you need to kill the job manually, ideally by calling kill().
autodelete set to false
to disable automatic deletion of the job.
See also isAutoDelete().
[protected]
void KJob::setCapabilities(KJob::Capabilities capabilities)
Sets the capabilities for this job.
capabilities are the capabilities supported by this job
See also capabilities().
[protected]
void KJob::setError(int errorCode)
Sets the error code.
It should be called when an error is encountered in the job, just before calling emitResult().
You should define an (anonymous) enum of error codes, with values starting at KJob::UserDefinedError, and use those. For example,
enum { InvalidFoo = UserDefinedError, BarNotFound, };
errorCode the error code
See also error() and emitResult().
[protected]
void KJob::setErrorText(const QString &errorText)
Sets the error text.
It should be called when an error is encountered in the job, just before calling emitResult().
Provides extra information about the error that cannot be determined directly from the error code. For example, a URL or filename. This string is not normally translatable.
errorText the error text
See also errorText(), emitResult(), errorString(), and setError().
[since 5.92]
void KJob::setFinishedNotificationHidden(bool hide = true)
This method can be used to indicate to classes listening to signals from a job that they should ideally show a progress bar, but not a finished notification.
For example when opening a remote URL, a job will emit the progress of the download, which can be used to show a progress dialog or a Plasma notification, then when the job is done it'll emit e.g. the finished signal. Showing the user the progress dialog is useful, however the dialog/notification about the download being finished isn't of much interest, because the user can see the application that invoked the job opening the actual file that was downloaded.
This function was introduced in 5.92.
See also isFinishedNotificationHidden().
[protected]
void KJob::setPercent(unsigned long percentage)
Sets the overall progress of the job. The percent() signal is emitted if the value changed.
The job takes care of this if you call setProcessedAmount in Bytes (or the unit set by setProgressUnit). This method allows you to set your own progress, as an alternative.
percentage the new overall progress
See also percent().
[protected]
void KJob::setProcessedAmount(KJob::Unit unit, qulonglong amount)
Sets the processed size. The processedAmount() and percent() signals are emitted if the values changed. The percent() signal is emitted only for the progress unit.
unit the unit of the new processed amount
amount the new processed amount
See also processedAmount().
[protected, since 5.76]
void KJob::setProgressUnit(KJob::Unit unit)
Sets the unit that will be used internally to calculate the progress percentage. The default progress unit is Bytes.
This function was introduced in 5.76.
[protected]
void KJob::setTotalAmount(KJob::Unit unit, qulonglong amount)
Sets the total size. The totalSize() and percent() signals are emitted if the values changed. The percent() signal is emitted only for the progress unit.
unit the unit of the new total amount
amount the new total amount
See also totalAmount().
void KJob::setUiDelegate(KJobUiDelegate *delegate)
Attach a UI delegate to this job.
If the job had another UI delegate, it's automatically deleted. Once attached to the job, the UI delegate will be deleted with the job.
delegate the new UI delegate to use
See also uiDelegate() and KJobUiDelegate.
[signal]
void KJob::speed(KJob *job, unsigned long speed)
Emitted to display information about the speed of this job.
Note: This is a private signal, it shouldn't be emitted directly by subclasses of KJob, use emitSpeed() instead.
job the job that emitted this signal
speed the speed in bytes/s
[pure virtual]
void KJob::start()
Starts the job asynchronously.
When the job is finished, result() is emitted.
Warning: Never implement any synchronous workload in this method. This method should just trigger the job startup, not do any work itself. It is expected to be non-blocking.
This is the method all subclasses need to implement. It should setup and trigger the workload of the job. It should not do any work itself. This includes all signals and terminating the job, e.g. by emitResult(). The workload, which could be another method of the subclass, is to be triggered using the event loop, e.g. by code like:
void ExampleJob::start() { QTimer::singleShot(0, this, &ExampleJob::doWork); }
[protected, since 6.8]
void KJob::startElapsedTimer()
Starts the internal elapsed time measurement timer.
Sub-classes must call startElapsedTimer() from their start() implementation, to get elapsedTime() measurement. Otherwise elapsedTimer() method will always return 0.
This function was introduced in 6.8.
[slot]
bool KJob::suspend()
Suspends this job.
The job should be kept in a state in which it is possible to resume it.
Returns true
if the operation is supported and succeeded, false
otherwise
qulonglong KJob::totalAmount(KJob::Unit unit) const
Returns the total amount of a given unit for this job.
unit the unit of the requested amount
See also setTotalAmount().
[signal]
void KJob::totalSize(KJob *job, qulonglong size)
Emitted when we know the size of this job (data size in bytes for transfers, number of entries for listings, etc).
Note: This is a private signal, it shouldn't be emitted directly by subclasses of KJob, use setTotalAmount() instead.
job the job that emitted this signal
size the total size
KJobUiDelegate *KJob::uiDelegate() const
Returns the delegate attached to this job, or nullptr
if there's no such delegate
See also setUiDelegate().
[signal]
void KJob::warning(KJob *job, const QString &message)
Emitted to display a warning about this job.
job the job that emitted this signal
message the warning message