简体   繁体   English

普通Qt应用程序中的Qt Qml

[英]Qt Qml in a normal Qt application

I have a QListView with a custom ListviewDelegate::paint implemented to do custom painting of items. 我有一个带有自定义ListviewDelegate :: paint的QListView,实现了对项目的自定义绘制。

I wonder if its possible to crete a qml file defining a rectangle and use that for painting each item? 我想知道是否有可能创建一个定义矩形的qml文件并将其用于绘制每个项目? This would give me some freedom to create decent looking items in my listview compared to using the QPainter. 与使用QPainter相比,这使我在创建列表视图中的外观时有更多的自由。

looks like its possible. 看起来可能。 using following code you can load QML element as QDeclarativeView. 使用以下代码,您可以将QML元素加载为QDeclarativeView。 Which is derived from QWidget, so you can paint that widget from your deletegate. 这是从QWidget派生的,因此您可以从deletegate绘制该小部件。

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

Derive from a QDeclarativeItem and override paint method. QDeclarativeItem派生并重写paint方法。 Register this new component with qmlRegisterType and use it inside your delegate. 使用qmlRegisterType注册此新组件,并在您的委托中使用它。

Don't forget to unset flag QGraphicsItem::ItemHasNoContents in your custom component item. 不要忘记在自定义组件项目中取消设置QGraphicsItem::ItemHasNoContents标志。

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): 查看器代码(在main内,设置QML源之前):

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

And QML code: 和QML代码:

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
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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