Development/Tutorials/Plasma4/QML/API

From KDE TechBase
Revision as of 17:29, 30 October 2011 by Mart (talk | contribs) (→‎Theme)

Introduction to the Plasmoid QML Declarative API

This document provides an overview/reference of the Declarative QML API for Plasmoids. It isn't a full binding to all of Qt or KDE's libraries, but a focused set of bindings designed to make writing Plasmoids fast and easy, while remaining powerful.

The API in this documentation covers the API of the Plasma specific QML components, so only the Declarative part of the API.

The QML ScriptEngine is based upon the Plasma JavaScript engine, making the API of the JavaScript part identical to the one of the JavaScript plasmoids engine. To see the api of the global Plasmoid object, see the JavaScript API documentation. (TODO: the JavaScript api page should probably be copied and stripped down the imperative bits not present there, it would make it harder to update tough)

What Is a Declarative Plasmoid?

To denote that this Plasmoid is a Declarative widget, ensure that in the metadata.desktop file there is this line:

X-Plasma-API=declarativeappletscript

What follows is a description of the Plasma declarative classes instantiable from QML.

Main Plasma QML Classes

Data Engines

While it's possible to fetch data from a Plasma DataEngine in the same way as the JavaScript API, it is preferrable to use the following declarative classes:

DataSource

DataSource is a receiver for a dataEngine and can be declared inside QML:

 import org.kde.plasma.core 0.1 as PlasmaCore

 PlasmaCore.DataSource {
     id: dataSource
     engine: "time"
     connectedSources: ["Local"]
     interval: 500
 }

Properties

It has the following properties:

  • bool valid (read only): true when the DataSource is successfully connected to a data engine
  • int interval: interval of polling of the dataengine, if 0 (default value, so no need to specify if you don't need it) no polling will be executed
  • string engine: the plugin name of the dataengine to load, e.g. "nowplaying", etc.
  • Array(string) connectedSources: all the sources of the dataengine we are connected to (and whose data will appear in the data property)
  • Array(string) sources (read only): all the sources available from the dataengine
  • variant map data (read only): It's the most important property, it's a map of all the data available from the dataengine: its structure will be as follows:
    • each key of the map will be a source name, in connectedSources
    • each value will be a variant hash, so an hash with strings as keys and any variant as value
    • example: dataSource.data["Local"]["Time"] indicates the Time key of the dataengine source called "Local"

Signals

It has the following signals:

Note that javascript/qml applies the 'on' prefix to signals. So the actual signal name in C++ which is e.g. newData(...) becomes onNewData(...).

  • onNewData(String sourceName, Plasma::DataEngine::Data data)
  • onSourceAdded(String source)
  • onSourceRemoved(String source)
  • onSourceConnected(String source)
  • onSourceDisconnected(String source)
  • onIntervalChanged()
  • onEngineChanged()
  • onDataChanged()
  • onConnectedSourcesChanged()
  • onSourcesChanged()

Methods

It has the following methods:

  • StringList keysForSource(String source): lists all the keys corresponding to a certain source: for instance in the "time" dataengine, for the "Local" source, keys will be:
    • "Timezone Continent"
    • "Offset"
    • "Timezone"
    • "Time"
    • "Date"
    • "Timezone City"
  • Service serviceForSource(String source): returns a Plasma service that corresponds a given source: see the section about services for how to use it.
  • void connectSource(String source): adds to connectedSources the new source
  • void disconnectSource(String source): removes that source from connectedSources

Service

Due to their imperative nature, Plasma Services are not instantiated as QML classes, but rather created out of a DataSource with the method serviceForSource and used in the JavaScript portions of the QML files. This following example is a simplified version from the Now Playing QML widget in the kdeexamples git repository:

  var service = dataSource.serviceForSource(activeSource)
  var operation = service.operationDescription("seek")
  operation.seconds = 10

  var job = service.startOperationCall(operation)

Here dataSource is the id of a DataSource object, and activeSource is a source contained in one of its connectedSources. The service provides an operation called "seek", with a parameter called "seconds", that can be written on it as a property of a JavaScript object.

ServiceJob

It is necessary to monitor the result of a Service operation, it's possible to connect to the finished signal provided by the job return paramenter of the startOperationCall service method. The finished signal has the same job as parameter, from which is possible to check the variant result property, to check the result.

DataModel

Some data engines return as their data something that can be interpreted as a list of items, rather than simple key/value pairs. QML provides some item views such as ListView, GridView and Repeater. The DataModel QML object can provide, based on a DataSource a model suitable for those QML item views.

It has the following properties:

  • DataSource dataSource: the id of an existing (and connected) DataSource
  • String sourceFilter: it's a regular expression. If the DataSource is connected to more than one source, only inserts data from sources matching this filter expression in the model. To, for example, have a source watch all sources beginning with say "name:", the required regexp would be sourceFilter: "name:.*"
  • String keyRoleFilter: it's a regular expression. Only data with keys that match this filter expression will be inserted in the model
  • int count (read only): how many items are in the model


Example:

 ListView {
   model: PlasmaCore.DataModel {
        dataSource: microblogSource
        keyRoleFilter: "[\\d]*"
    }
    delegate: Text {
        text: title
    }
 }

In the example, microblogSource is the id of a DataSource, and inserts in the model only entries that have a number as the key name (matched with [\\d]*, in this case tweets ids)

Each item in the model will have the form of a variant hash: all the keys of the hash will be registered as model role names, in the example, "title" is a role of the model containing a string (also reachable with model["title"]).

A special reserved role will always be present: "DataEngineSource": it will contain the name of the data engine source that gave origin to this item. Therefore, if you want merely the string of the current source that the model is at...do model["DataEngineSource"].

Note that view.currentItem holds the item currently selected. However, due to (http://bugreports.qt.nokia.com/browse/QTBUG-16347) this does not work in PathView. A workaround is to make your own.

SortFilterModel

SortFilterModel is a proxy model for easy sorting and/or filtering of the items in a DataModel (or any other QAbstractItemModel subclass that has been registered in QML with setContextProperty from a C++ application) Properties:

  • model sourceModel
  • String filterRegExp
  • String filterRole
  • String sortRole
  • Qt::SortOrder sortOrder
  • int count (read only)

Popup Applet

So you want your QML applet to be a popup applet, like the device notifier (an icon in the panel shows and expands the applet)?

Why, that's easy.

To change your plasmoid from being a regular boring one, in your metadata.desktop, simply change this following line:

ServiceTypes=Plasma/Applet

To:

ServiceTypes=Plasma/Applet,Plasma/PopupApplet

Then in the main QML item's Component.onCompleted, do:

    plasmoid.popupIcon = "konqueror"

Plasma Themes

Theme

This class instantiable from QML provides access to the Plasma Theme colors and other facilities such as fonts. From KDE 4.8 a Theme instance is always present, is not necessary to create it by hand. It has the following properties:

  • String themeName (read only)
  • bool windowTranslucentEnabled (read only)
  • Url homepage (read only)
  • bool useGlobalSettings (read only)
  • QString wallpaperPath (read only)
  • color textColor (read only)
  • color highlightColor (read only)
  • color backgroundColor (read only)
  • color buttonTextColor (read only)
  • color buttonBackgroundColor (read only)
  • color linkColor (read only)
  • color visitedLinkColor (read only)
  • color visitedLinkColor (read only)
  • color buttonHoverColor (read only)
  • color buttonFocusColor (read only)
  • color viewTextColor (read only)
  • color viewBackgroundColor (read only)
  • color viewHoverColor (read only)
  • color viewFocusColor (read only)
  • String styleSheet (read only)
  • Font defaultFont (read only)
  • Font desktopFont (read only)
  • Font smallestFont (read only)

Properties of Font:

  • bool bold
  • Capitalization capitalization (MixedCase, AllUppercase, AllLowercase, SmallCaps, Capitalize) (read only)
  • String family (read only)
  • bool italic (read only)
  • real letterSpacing (read only)
  • int pixelSize (read only)
  • real pointSize (read only)
  • bool strikeout (read only)
  • bool underline (read only)
  • Weight weight (Light, Normal, DemiBold, Bold, Black) (read only)
  • real wordSpacing (read only)

Svg

Declaring a Svg element instantiates a Plasma Svg instance. This class doesn't draw anything. For drawing, SvgItem is used. Properties:

  • QSize size
  • bool multipleImages
  • String imagePath can be anything in the desktoptheme/ folder. For more information on what is available, see Plasma Theme Elements
  • bool usingRenderingCache

Methods:

  • QPixmap pixmap(QString elementID)
  • void resize(qreal width, qreal height)
  • void resize(): resets the image to its default dimension
  • QSize elementSize(QString elementId)
  • QRectF elementRect(QString elementId)
  • bool hasElement(QString elementId)
  • bool isValid(): true if valid svg file

Sample Code:

    PlasmaCore.Svg {
        id: mySvg
        imagePath: "widgets/line"
    }

SvgItem

It's a graphical element that will actually paint a Svg instance. Properties:

  • String elementId: what element to render. If null, the whole svg will be rendered
  • Svg svg: instance of the Svg class mentioned above
  • QSizeF naturalSize (read only): default size of the Svg
  • bool smooth: paint with antialias (default false)

Sample Code:

    PlasmaCore.SvgItem {
        id: mySvgItem
        anchors {
            top: parent.top
            left: parent.left
        }

        width: 300
        height: 3

        svg: mySvg
        elementId: "horizontal-line"
    }

FrameSvgItem

It's a graphical element that paints a Plasma::FrameSvg, so a rectangular image composed by 9 elements contained in a Svg file, useful for things like buttons and frames.

Flags

  • EnabledBorders: combination of TopBorder | BottomBorder | LeftBorder | RightBorder, NoBorder if no border of the frame is enabled

Properties:

  • String imagePath: path of the file relative to the Plasma Theme, for instance "widgets/background"
  • String prefix: a FrameSvg can contain multiple frames, for instance a button contains "normal", "raised" and "pressed"
  • Margins margins (read only): the margins of the frame, see documentation below
  • EnabledBorders enabledBorders: what borders are enabled

Margins

Properties:

  • real left (read only)
  • real top (read only)
  • real right (read only)
  • real bottom (read only)

Sample Code:

PlasmaCore.FrameSvgItem {
    id: myFrameSvgItem
    anchors.fill: parent
    imagePath: "translucent/dialogs/background"
}

Top Level windows

Dialog

Dialog instantiates a Plasma::Dialog, it will be a Plasma themed top level window that can contain any QML component.

Properties:

  • Item mainItem: the Item contained in the Dialog, it can be any QML Item instance
  • bool visible: if the window (not the mainItem) is visible
  • int x: x position of the window in screen coordinates
  • int y: y position of the window in screen coordinates
  • int width (read only): total width of the dialog, including margins
  • int height (read only): total height of the dialog, including margins
  • int windowFlags: Qt window flags of the Dialog
  • Margins margins (read only): margins of the Dialog

Methods:

  • QPoint popupPosition(Item item, Qt::Alignment alignment=Qt::AlignLeft): the suggested position for the Dialog if it has to be correctly placed as popup of the QML item passed as parameter.
  • void setAttribute(Qt::WindowAttribute attribute, bool on): set an attribute for the dialog window

Margins

Properties:

  • real left (read only)
  • real top (read only)
  • real right (read only)
  • real bottom (read only)

ToolTip

Declaring a ToolTip instance makes it possible to use Plasma tooltips with any QML item.

Properties:

  • Item target: the QML item we want to show a tooltip of
  • String mainText
  • String subText
  • String image: freedesktop compliant icon name as image of the tooltip

Plasma QtComponents (4.8)

TODO