Posted on 2011-08-04 21:59
RTY 閱讀(634)
評論(0) 編輯 收藏 引用 所屬分類:
轉載隨筆 、
QML
1.假設這樣一種情況
我這里由一個Wideget 繼承自QWidget上面添加來一個QLabel, 一個QPushButton
我如何把這個Wideget放到QML中使用,那么我當QPushButton 按下后我怎么在QML中進行處理呢?
我這里指出一種方法
讓Wideget 繼承QGraphicsProxyWidget,對Wideget進行導出,在QML中創建
此對象,在他導出的信中進行處理,具體代碼。
還有就是這個網址上說明來很多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;
// 關鍵在這里,當一個信號導出后他的相應的名字就是第1個字母大寫,前面在加上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" }
}
} |
說明:
這里實現的是當QPushButton按鈕按下后,獲取QML中TextInput上的文本,
對QLabel進行設置,關鍵點在于Widget中的信號函數sendOnButton, 他導出后在QML中
將引發的是onSendOnButton 只要在QML中對這個編寫處理就可以實現,具體看代碼。