2012-02-22 63 views
0

我有一個QListView自定義ListviewDelegate :: paint實現自定義繪畫的項目。Qt Qml在一個正常的Qt應用程序

我不知道是否有可能克里特定義一個矩形的qml文件,並使用它來繪製每個項目?與使用QPainter相比,這會給我一些自由來在我的列表視圖中創建體面的項目。

回答

1

看起來可能。使用以下代碼可以將QML元素加載爲QDeclarativeView。這是從QWidget派生的,所以你可以從你的deletegate中繪製這個小部件。

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

我已經試過了,但顯示的qml只是全白。沒有內容顯示 – 2012-02-23 16:06:28

+1

沒有看到輸出窗口中的錯誤輸出。解決它,是的項目顯示。 – 2012-02-23 16:10:32

1

衍生自QDeclarativeItem並覆蓋paint方法。用qmlRegisterType註冊這個新組件並在代理中使用它。

不要忘記在您的自定義組件項目中取消設置標誌QGraphicsItem::ItemHasNoContents

組件代碼:

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代碼(內部主,設置QML源之前):

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

和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 
     } 
    } 
} 
+0

這不是我所問的相反嗎?我想在我的QtGui應用程序中加載一個QML項目並用作我的QListView的項目? – 2012-02-23 15:01:12

+0

進口Self 1.0中的Self 1.0是什麼? – 2012-02-23 16:13:40

+0

對不起,我誤解了這個問題。 「Self」是與'qmlRegisterType'一起使用的任意QML模塊名稱。 – sergk 2012-02-24 10:45:52