测试环境: Qt 5.5.1 msvc2010
新建VS工程, Qt Gui项目(项目名字这里是QtFirst)
UI界面
设计ui界面, 如图
因为是双向测试, 所以先来个按钮, 把pushButton的clicked信号连接到QtFirst的槽
项目代码
QtFirst.h
class QtFirst : public QMainWindow
{
Q_OBJECT
public:
QtFirst(QWidget *parent = 0);
~QtFirst();
private:
Ui::QtFirstClass ui;
protected slots:
void slot1();// 响应pushButton的clicked信号
void onTest1(QString str);// 响应QML的test1信号
signals:
void test2(QVariant str);// 触发QML的onTest2槽
};
QtFirst.cpp
QtFirst::QtFirst(QWidget *parent) : QMainWindow(parent)
{
ui.setupUi(this);
QQuickView *QuickView = new QQuickView(QUrl("qrc:/qml/main.qml"));
QWidget *ViewContainer = QWidget::createWindowContainer(QuickView, this);
ViewContainer->setGeometry(0, 0, 300, 200);
QQuickItem* rootObject = QuickView->rootObject();
connect(rootObject, SIGNAL(test1(QString)), this, SLOT(onTest1(QString)));
connect(this, SIGNAL(test2(QVariant)), rootObject, SLOT(onTest2(QVariant)));
}
QtFirst::~QtFirst()
{
}
void QtFirst::onTest1(QString str)
{
qDebug() << str;
}
void QtFirst::slot1()
{
test2("abcdef");
}
main.qml
import QtQuick 2.5
Rectangle {
id: frame
x: 0
y: 0
width: 300
height: 200
color: "steelblue"
signal test1(string str);
function onTest2(str) {
textInput1.text = str;
}
MouseArea {
x: 0
y: 90
width: 80
height: 20
cursorShape: Qt.IBeamCursor
TextInput {
id: textInput1
anchors.fill: parent
text: qsTr("Text Input")
Keys.onReturnPressed: {
frame.test1(this.text);
}
}
}
}
代码解释
1. QML
QML中的信号用signal声明, 槽用function声明
特别的, 槽函数的声明没有变量类型, 因为QML类似JS, 只有值有类型, 变量没有类型
2. C++
使用QQuickView动态创建QML视图, 之所以不用QQuickWidget控件, 是因为中文输入有问题(有知道如何解决的朋友可以说一下)
通过rootObject方法取得最顶层对象, 即id为frame的那个Rectangle, 测试时发现通过findchild拿不到(即使设置了objectName)
使用connect连接信号/槽
3. 其他
QML的信号, 变量有类型
QML的槽, 变量没有类型, C++的信号在声明时参数统一用QVariant类型
完结
本人也是刚接触这一块, 如果哪里不对, 请及时指出