QML與c++交互學(xué)習(xí)筆記(七)
Posted on 2011-08-04 21:59 RTY 閱讀(644) 評(píng)論(0) 編輯 收藏 引用 所屬分類: 轉(zhuǎn)載隨筆 、QML1.假設(shè)這樣一種情況
我這里由一個(gè)Wideget 繼承自QWidget上面添加來一個(gè)QLabel, 一個(gè)QPushButton
我如何把這個(gè)Wideget放到QML中使用,那么我當(dāng)QPushButton 按下后我怎么在QML中進(jìn)行處理呢?
我這里指出一種方法
讓Wideget 繼承QGraphicsProxyWidget,對(duì)Wideget進(jìn)行導(dǎo)出,在QML中創(chuàng)建
此對(duì)象,在他導(dǎo)出的信中進(jìn)行處理,具體代碼。
還有就是這個(gè)網(wǎng)址上說明來很多QML與c++之間通訊的方法,很悲劇的是我的assistant中卻沒有者部分,不知道版本低還是怎么的。
http://doc.qt.nokia.com/4.7-snapshot/qtbinding.html
2.具體代碼
//widget.h #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QGraphicsProxyWidget> #include <QPushButton> #include <QLabel> #include <QLineEdit> class Widget : public QGraphicsProxyWidget { Q_OBJECT public: explicit Widget(QGraphicsItem *parent = 0); ~Widget(); Q_INVOKABLE void changeText(const QString& s); signals: void sendOnButton(void); private: QPushButton *m_Btn; QLabel *m_Label; QWidget *m_MainWidget; }; #endif // WIDGET_H |
//widget.cpp #include "widget.h" Widget::Widget(QGraphicsItem *parent) : QGraphicsProxyWidget(parent) { m_MainWidget = new QWidget; m_Btn = new QPushButton(m_MainWidget); m_Label = new QLabel(m_MainWidget); m_Btn->setText("PushButton"); m_Btn->setGeometry(10, 10, 100, 30); m_Label->setGeometry(10, 40, 200, 30); QObject::connect(m_Btn, SIGNAL(clicked()), this, SIGNAL(sendOnButton())); setWidget(m_MainWidget); } Widget::~Widget() { delete m_MainWidget; } void Widget::changeText(const QString& s) { m_Label->setText(s); qDebug(" call Widget::changeText"); } |
// main.cpp #include <QtGui/QApplication> #include <QtDeclarative/QDeclarativeView> #include <QtDeclarative/QDeclarativeEngine> #include <QtDeclarative/QDeclarativeComponent> #include <QtDeclarative/QDeclarativeContext> #include "widget.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); qmlRegisterType<Widget>("UIWidget", 1, 0, "Widget"); QDeclarativeView qmlView; qmlView.setSource(QUrl::fromLocalFile("../UICtest/UICtest.qml")); qmlView.show(); return a.exec(); } |
// UICtest.qml import Qt 4.7 import UIWidget 1.0 Rectangle { width: 640 height: 480 color: "black" Widget { id: uiwidget; x: 100; y: 100; width: 400; height: 100; // 關(guān)鍵在這里,當(dāng)一個(gè)信號(hào)導(dǎo)出后他的相應(yīng)的名字就是第1個(gè)字母大寫,前面在加上on // 例如 clicked -- onClicked colorchange --onColorchange; onSendOnButton: { uiwidget.changeText(textinput.text); } } Rectangle{ x: 100; y: 20; width: 400; height: 30; color: "blue" TextInput {id: textinput; anchors.fill: parent; color: "white" } } } |
說明:
這里實(shí)現(xiàn)的是當(dāng)QPushButton按鈕按下后,獲取QML中TextInput上的文本,
對(duì)QLabel進(jìn)行設(shè)置,關(guān)鍵點(diǎn)在于Widget中的信號(hào)函數(shù)sendOnButton, 他導(dǎo)出后在QML中
將引發(fā)的是onSendOnButton 只要在QML中對(duì)這個(gè)編寫處理就可以實(shí)現(xiàn),具體看代碼。