简体   繁体   中英

Qt Qml in a normal Qt application

I have a QListView with a custom ListviewDelegate::paint implemented to do custom painting of items.

I wonder if its possible to crete a qml file defining a rectangle and use that for painting each item? This would give me some freedom to create decent looking items in my listview compared to using the QPainter.

looks like its possible. using following code you can load QML element as QDeclarativeView. Which is derived from QWidget, so you can paint that widget from your deletegate.

 QDeclarativeView *qmlView = new QDeclarativeView;
 qmlView->setSource(QUrl::fromLocalFile("myqml.qml"));

Derive from a QDeclarativeItem and override paint method. Register this new component with qmlRegisterType and use it inside your delegate.

Don't forget to unset flag QGraphicsItem::ItemHasNoContents in your custom component item.

Component code:

class CustomItem : public QDeclarativeItem
{
    Q_OBJECT
    Q_PROPERTY (int radius READ radius WRITE setRadius)
public:
    explicit CustomItem(QDeclarativeItem *parent = 0)
      : QDeclarativeItem(parent), m_radius(0)
    {
        setFlag(QGraphicsItem::ItemHasNoContents, false);
    }
    void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
    void setRadius(int r);
    int radius();
private:
    int m_radius;
};

Viewer code (inside main, before setting QML source):

qmlRegisterType<CustomItem>("Self", 1,0, "CustomItem");

And QML code:

import QtQuick 1.1
import Self 1.0
ListView {
    model: ListModel {
        ListElement { name: "One";   value: 10 }
        ListElement { name: "Two";   value: 5 }
        ListElement { name: "Three"; value: 15 }
    }
    delegate: Column {
        Text {
            text: name
        }
        CustomItem {
            radius: value
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM