基础很差去公司做网站,公司网站的定义,工程建设项目招标范围和规模标准规定,陕西交通建设有限公司网站文章目录 一、demo效果图二、c和qml交互的基本方式1、qml 调用 C 类对象2、C 类对象调用 qml3、qml 给 C 发送信号4、C 给 qml 发送信号 三、关键代码1、工程结构图2、c代码MainWindow.cppMainQuickView.cppStudentInfoView.cppStudentInfoModel.cpp 3、qml代码main.qmlMainQui… 文章目录 一、demo效果图二、c和qml交互的基本方式1、qml 调用 C 类对象2、C 类对象调用 qml3、qml 给 C 发送信号4、C 给 qml 发送信号 三、关键代码1、工程结构图2、c代码MainWindow.cppMainQuickView.cppStudentInfoView.cppStudentInfoModel.cpp 3、qml代码main.qmlMainQuickTopRect.qmlMainQuickMiddleRect.qmlMainQuickMiddleTableRect.qml 一、demo效果图
该实例主要是在已有的QWidget工程中加入qml工程方便qml项目的开发与维护让qml开发者更好的上手qml。
1展示了c和qml常见的交互方式。 2qwidget工程如何加载qml工程如何加载自己实现的qml tool库。 3创建无边框qml界面支持拖拽窗口的缩小与展开界面的分段实现。 4展示一个简单的堆栈窗口SwipeView相当于QStackedWidget管理多个子窗口页面。 5实现一个简单的列表框ListView相当于QListWidget定时请求网络数据展示学生信息将view和model进行分离降低界面与数据的耦合。 6点击学号、年龄实现了列表数据的排序。 二、c和qml交互的基本方式
两者的交互是核心简单学习后可以快速上手。方式有很多种有的比较繁杂不易理解此处只使用了最方便使用的方法满足基本的交互。基本的方式不外乎有四种。
qml 调用 C 类对象C 类对象调用 qmlqml 给 C 发送信号C 给 qml 发送信号
1、qml 调用 C 类对象
需要先将C类MainQuickView、MyWindow注册。和qml相关的C类最好都进行注册。
// cpp
class MainQuickView : public QQuickView
{Q_OBJECT
public:MainQuickView(QQuickView *parent nullptr);~MainQuickView() override;void initialzeUI();
protected:
};void MainQuickView ::initialzeUI()
{// 注册为了qml中可以直接访问C对象this-rootContext()-setContextProperty(myQuickView, this);MyWindow *w new MyWindow();this-rootContext()-setContextProperty(myWindow, w);...
}这样C的信号public槽函数Q_INVOKABLE 修饰的类成员函数
// cpp
class MyWindow : public QWidget
{Q_OBJECTpublic:MyWindow();// Q_INVOKABLE可以将C函数暴漏给qml引擎注册到元对象系统Q_INVOKABLE void invokableMethod();signals:void dataChanged();public slots:void refresh();
};就可以在qml中调用
// main.qml
Rectangle {id: rootwidth: 1200height: 800onClicked: {myWindow.showNormal(); // showNormal是QWidget父类的槽函数}
}2、C 类对象调用 qml
需要先找到你想访问的qml中名为topRect的QQuickItem对象
// cpp
QQuickItem* topRect this-rootObject()-findChildQQuickItem*(topRect);然后再访问qml实现的函数“setTitleText”该函数标题3展示(qml 给 C 发送信号)
// cpp
QMetaObject::invokeMethod(topRect, setTitleText, Q_ARG(QVariant, QString::fromLocal8Bit(Qml窗口标题)));3、qml 给 C 发送信号
qml发送信号
// qml
Rectangle {id: rootsignal sendTopRectPos(var x, var y) // 定义信号function setTitleText(text) {titleText.text text}MouseArea {// ... property point clickPos: 0, 0onPressed: {clickPos Qt.point(mouse.x, mouse.y)}onPositionChanged: {var delta Qt.point(mouse.x - clickPos.x, mouse.y - clickPos.y)sendTopRectPos(delta.x, delta.y) // 发送信号}}
}C绑定槽函数该操作可以实现无边框窗口的拖拽
// cpp
QQuickItem* topRect this-rootObject()-findChildQQuickItem*(topRect);if (topRect) {connect(topRect, SIGNAL(sendTopRectPos(QVariant, QVariant)),this, SLOT(onSendTopRectPos(QVariant, QVariant)));4、C 给 qml 发送信号
C发送信号
// cpp
void MainQuickView::minMaxQmlWindow()
{int nStudent 10;emit refreshStuCount(nStudent); // 发送信号
}qml绑定槽函数
// qml
Rectangle {id: rootfunction onRefreshStuCount(nStudent){// ...}Component.onCompleted: {mainQuickView.refreshStuCount.connect(onRefreshStuCount) // 绑定qml函数}三、关键代码
1、工程结构图 2、c代码
MainWindow.cpp
MainWindow::MainWindow(QWidget *parent): QWidget(parent), ui(new Ui::MainWindow), m_pQuickVew(nullptr)
{ui-setupUi(this);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_pushButton_clicked()
{if (!m_pQuickVew){// 加载qml包含两种方式一种是QQuickView一种是QQmlApplicationEngine// 当前使用第一种方式MainQuickView继承自QQuickViewm_pQuickVew new MainQuickView();m_pQuickVew-setObjectName(quickView);}m_pQuickVew-show();
}MainQuickView.cpp
static const char* s_mainPath qrc:/qml/main.qml;MainQuickView::MainQuickView(QQuickView *parent): QQuickView(parent), m_bMin(false)
{this-setFlags(Qt::Window | Qt::FramelessWindowHint);this-setTitle(QString::fromLocal8Bit(图书馆));initialize();setMoveable();setTitleData();
}MainQuickView::~MainQuickView()
{
}void MainQuickView::initialize()
{// 初始化view 和 model降低耦合提高可维护性if (!m_pStudentInfoView)m_pStudentInfoView new StudentInfoView();if (!m_pStudentInfoModel)m_pStudentInfoModel m_pStudentInfoView-getStudentInfoMode();// ...其他功能initialzeUI();
}void MainQuickView::initialzeUI()
{// 注册qml中可以直接访问C对象this-rootContext()-setContextProperty(mainQuickView, this);// qml可以通过studentInfoView去使用其实现的函数this-rootContext()-setContextProperty(studentInfoView, m_pStudentInfoView);this-rootContext()-setContextProperty(studentInfoModel, m_pStudentInfoModel);// qml根对象大小随窗口大小改变而改变this-setResizeMode(QQuickView::SizeRootObjectToView);// 导入自定义模块工具this-engine()-addImportPath(:/qmlTools);// 设置准备加载得qml文件相当于c的main函数入口this-setSource(QUrl(s_mainPath));
}void MainQuickView::minMaxQmlWindow()
{m_bMin !m_bMin;emit minQmlWindow(m_bMin);
}void MainQuickView::onSendTopRectPos(QVariant pX, QVariant pY)
{this-setX(this-x() pX.toInt());this-setY(this-y() pY.toInt());
}void MainQuickView::onCloseQuickView()
{close();
}void MainQuickView::onShowMinimized()
{showMinimized();
}void MainQuickView::setMoveable()
{// 当移动qml窗口时将移动坐标告诉C// 找到对象名叫topRect的qmlC绑定qml的信号QQuickItem* topRect this-rootObject()-findChildQQuickItem*(topRect);if (topRect) {connect(topRect, SIGNAL(sendTopRectPos(QVariant, QVariant)),this, SLOT(onSendTopRectPos(QVariant, QVariant)));}
}void MainQuickView::setTitleData()
{// 找到对象名叫topRect的qmlC向qml发送消息触发qml中实现的setTitleText函数QQuickItem* topRect this-rootObject()-findChildQQuickItem*(topRect);QMetaObject::invokeMethod(topRect, setTitleText, Q_ARG(QVariant, QString::fromLocal8Bit(Qml窗口标题)));
}StudentInfoView.cpp
StudentInfoView::StudentInfoView(QObject *parent): QObject(parent), m_sortType(StudentInfoSort::sortNone)
{if (!m_pStudentInfoModel)m_pStudentInfoModel new StudentInfoModel(this);// 如果数据来自网络就需要定时请求接口并更新界面m_timer new QTimer(this);m_timer-setInterval(10 * 1000);QObject::connect(m_timer, QTimer::timeout, this, StudentInfoView::onUpdateInfoData);onUpdateInfoData();m_timer-start();
}StudentInfoModel *StudentInfoView::getStudentInfoMode()
{return m_pStudentInfoModel;
}// qSort()比较函数不能定义为类成员函数参数包含隐藏的this指针会导致参数不符
// 可以定义为static类成员函数、static函数、普通函数
bool StudentInfoView::idAscend(const StudentInfoItem stu1, const StudentInfoItem stu2)
{return stu1.stuId stu2.stuId; //学号升序
}// 普通函数
bool idDescend(const StudentInfoItem stu1, const StudentInfoItem stu2)
{return stu1.stuId stu2.stuId; //学号降序
}bool ageAscend(const StudentInfoItem stu1, const StudentInfoItem stu2)
{return stu1.age stu2.age; //年龄升序
}void StudentInfoView::setSort(StudentInfoSort sortType)
{m_sortType sortType;if (m_sortType StudentInfoSort::sortIdAscend){qSort(m_allDatas.begin(), m_allDatas.end(), idAscend);}else if (m_sortType StudentInfoSort::sortIdDescend){qSort(m_allDatas.begin(), m_allDatas.end(), idDescend);}else if (m_sortType StudentInfoSort::sortAgeAscend){// 比较函数也可以写为lambda表达式qSort(m_allDatas.begin(), m_allDatas.end(),[](const StudentInfoItem stu1, const StudentInfoItem stu2){return stu1.age stu2.age;});}
}void StudentInfoView::updateSort(int sortType)
{// qml调用执行哪一种排序方式并刷新数据setSort((StudentInfoSort)sortType);if (m_pStudentInfoModel)m_pStudentInfoModel-clear();for (auto studentInfo : m_allDatas) {if (m_pStudentInfoModel) {m_pStudentInfoModel-AddModel(studentInfo);}}
}void StudentInfoView::onUpdateInfoData()
{// 每隔十秒请求网络接口根据返回的数据刷新model该实例模拟网络数据m_allDatas.clear();if (m_pStudentInfoModel)m_pStudentInfoModel-clear();QVectorStudentInfoItem studentInfos;StudentInfoItem item1;item1.stuId 9704;item1.stuName QString::fromLocal8Bit(百里);item1.sex 1;item1.age 14;StudentInfoItem item2;item2.stuId 9207;item2.stuName QString::fromLocal8Bit(黄忠);item2.sex 1;item2.age 26;StudentInfoItem item3;item3.stuId 9206;item3.stuName QString::fromLocal8Bit(鲁班);item3.sex 1;item3.age 17;StudentInfoItem item4;item4.stuId 9787;item4.stuName QString::fromLocal8Bit(女娲);item4.sex 0;item4.age 33;studentInfos item1 item2 item3 item4;m_allDatas studentInfos;setSort(m_sortType); //每一次网络数据刷新后执行保存的排序方式for (auto studentInfo : m_allDatas) {if (m_pStudentInfoModel) {m_pStudentInfoModel-AddModel(studentInfo);}}
}StudentInfoModel.cpp
#include StudentInfoModel.hStudentInfoModel::StudentInfoModel(QObject *parent): QAbstractListModel(parent)
{roleNames();
}StudentInfoModel::~StudentInfoModel()
{}void StudentInfoModel::clear()
{if (m_allDatas.size() 0)return;beginRemoveRows(QModelIndex(), 0, m_allDatas.size() - 1);m_allDatas.clear();endRemoveRows();
}void StudentInfoModel::mremove(int index)
{beginRemoveRows(QModelIndex(), index, index);m_allDatas.erase(m_allDatas.begin() index);endRemoveRows();
}void StudentInfoModel::update(int index, const StudentInfoItem infoModel)
{if (index 0 || m_allDatas.size() index)return;StudentInfoItem srcModel m_allDatas[index];srcModel infoModel;
}void StudentInfoModel::AddModel(const StudentInfoItem md)
{beginInsertRows(QModelIndex(), rowCount(), rowCount());m_allDatas.push_back(md);endInsertRows();
}QVariant StudentInfoModel::data(const QModelIndex index, int role) const
{if (index.row() 0 || index.row() m_allDatas.size()) {return QVariant();}const StudentInfoItem itemInfo m_allDatas.at(index.row());StudentInfoRoles infoRole static_castStudentInfoRoles(role);switch (infoRole) {case StudentInfoRoles::stuIdRole :return itemInfo.stuId;break;case StudentInfoRoles::stuNameRole :return itemInfo.stuName;break;case StudentInfoRoles::stuSexRole :return itemInfo.sex;break;case StudentInfoRoles::stuAgeRole :return itemInfo.age;break;default:return QVariant();break;}
}int StudentInfoModel::rowCount(const QModelIndex parent) const
{return m_allDatas.size();
}QHashint, QByteArray StudentInfoModel::roleNames() const
{// 映射C端的枚举与QML端的字符串QHashint, QByteArray data;data[int(StudentInfoRoles::stuIdRole)] stuId;data[int(StudentInfoRoles::stuNameRole)] stuName;data[int(StudentInfoRoles::stuSexRole)] sex;data[int(StudentInfoRoles::stuAgeRole)] age;return data;
}3、qml代码
main.qml
import QtQuick 2.0
import QtQuick.Layouts 1.0Item {id: rootwidth: 1200height: 800Rectangle {anchors.fill: parentcolor: redColumnLayout {spacing: 0MainQuickTopRect {id: topRectobjectName: topRectwidth: root.widthheight: 50}MainQuickMiddleRect {id: middleRectobjectName: middleRectwidth: root.widthheight: root.height - topRect.height}}}
}MainQuickTopRect.qml
import QtQuick 2.12
import QtQuick.Layouts 1.0
import QtQuick.Controls 2.12
import ../qmlTools/ButtonToolsRectangle {id: rootcolor: #181D33signal sendTopRectPos(var x, var y)function setTitleText(text) {titleText.text text}function onMinQmlWindow(bMin){if (bMin)narrowBtn.clicked() // narrowBtn是最小化按钮当然也可以直接mainQuickView.onShowMinimized()elsemainQuickView.showNormal()}Component.onCompleted: {mainQuickView.minQmlWindow.connect(onMinQmlWindow)}RowLayout {id: rowLayoutanchors.fill: rootanchors.leftMargin: 16anchors.rightMargin: 16Text {id: titleTextanchors.fill: rootanchors.left: rowLayout.leftverticalAlignment: Text.AlignVCenterhorizontalAlignment: Text.AlignHCentercolor: whitefont.pixelSize: 18font.family: Microsoft YaHei UIfont.bold: truetext: // 设置文本框背景颜色Rectangle {id: titleTextBackanchors.fill: titleTextcolor: #000000z: -1}}// 最小化ImageBtn {id: narrowBtnwidth: 24height: 24anchors.right: closeBtn.leftnormalUrl: qrc:/resource/minNormal.pnghoveredUrl: qrc:/resource/minHover.pngpressedUrl: qrc:/resource/minHover.pngonClicked: {mainQuickView.onShowMinimized();console.log(min);}}// 关闭ImageBtn {id: closeBtnwidth: 24height: 24anchors.right: rowLayout.rightnormalUrl: qrc:/resource/closeNormal.pnghoveredUrl: qrc:/resource/closeHover.pngpressedUrl: qrc:/resource/closeHover.pngonClicked: {mainQuickView.onCloseQuickView();}}}MouseArea {anchors.fill: parentacceptedButtons: Qt.LeftButtonpropagateComposedEvents: true //传递鼠标事件property point clickPos: 0, 0onPressed: {clickPos Qt.point(mouse.x, mouse.y)console.log(onPressed clickPos);}onPositionChanged: {var delta Qt.point(mouse.x - clickPos.x, mouse.y - clickPos.y)sendTopRectPos(delta.x, delta.y)}}
}MainQuickMiddleRect.qml
import QtQuick 2.0
import QtQuick 2.12
import QtQuick.Controls 1.2
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.2
import ../qmlTools/ButtonToolsRectangle {id: rootcolor: #2E3449property int oneCount: 50property int twoCount: 50property int threeCount: 50readonly property int pageWidth : 400Rectangle {id: titleSwitchBtnwidth: parent.width / 2anchors.top: parent.topanchors.topMargin: 30anchors.left: parent.leftanchors.leftMargin: width - width / 2height: 46color: #2C5CA5RowLayout {spacing: 20anchors.bottom: parent.bottomanchors.bottomMargin: 0anchors.left: parent.leftanchors.leftMargin: 40DownLineBtn { // qmlTool中自定义实现的下划线按钮id: cover_one_btnbtn_width: 100btn_string: qsTr(一班) oneCount qsTr(人)onMyClicked: {coverBtnStat(cover_one_btn, true)coverBtnStat(cover_two_btn, false)coverBtnStat(cover_three_btn, false)swipeView.currentIndex 0}}DownLineBtn {id: cover_two_btnbtn_width: 100btn_string: qsTr(二班) twoCount qsTr(人)onMyClicked: {coverBtnStat(cover_one_btn, false)coverBtnStat(cover_two_btn, true)coverBtnStat(cover_three_btn, false)swipeView.currentIndex 1}}DownLineBtn {id: cover_three_btnbtn_width: 100btn_string: qsTr(三班) threeCount qsTr(人)onMyClicked: {coverBtnStat(cover_one_btn, false)coverBtnStat(cover_two_btn, false)coverBtnStat(cover_three_btn, true)swipeView.currentIndex 2}}}}Rectangle {id: viewanchors.top: titleSwitchBtn.bottomanchors.topMargin: 4anchors.left: titleSwitchBtn.leftwidth: titleSwitchBtn.widthheight: pageWidthcolor: whiteradius: 4SwipeView {id: swipeViewobjectName: outSideSwipViewanchors.fill: parentcurrentIndex: 0clip: true //隐藏未选中的界面interactive: false //鼠标能否滑动Item { //St: 0第一页id: onePageRectangle {id: oneViewanchors.fill: parentcolor: #D7B9A1}}Item { //St: 1第二页id: twoPageMainQuickMiddleTableRect {id: tableViewcolor: greenwidth: titleSwitchBtn.widthheight: pageWidth}}Item { //St: 2第三页id: defaultPageRectangle {anchors.fill: parentcolor: #E6EC12radius: 4Text {text: qsTr(没有数据)font.pixelSize:16color: redfont.family: Microsoft YaHeiverticalAlignment: Text.AlignVCenterhorizontalAlignment: Text.AlignHCenteranchors.verticalCenter: parent.verticalCenteranchors.horizontalCenter: parent.horizontalCenter}}}}}Component.onCompleted: {// 初始化按钮状态coverBtnStat(cover_one_btn, true)coverBtnStat(cover_two_btn, false)coverBtnStat(cover_three_btn, false)}/* btn: object* st : modify state*/function coverBtnStat(btn, st) {btn.bold_st stbtn.show_line st}
}MainQuickMiddleTableRect.qml
import QtQuick 2.0
import ../qmlTools/ButtonTools
import QtQuick.Controls 1.4
import QtQuick.Controls 2.5Rectangle {id: winanchors.fill: parentcolor: greenproperty var current_numbers : 0property var stu_id_sort_state : 1property var stu_id_sort_open : false// 绘制表头Rectangle {id: table_Headheight: 48anchors.top: titleSwitchBtn.bottomRectangle {id: table_Textheight: 47 // 比整个表头高度小1为了容纳下划线TextShow {id: name_texttext: qsTr(姓名)anchors.left: table_Text.leftanchors.leftMargin: 68anchors.verticalCenter: table_Text.verticalCenter}TextShow {id: id_text// 学号未点击时显示↕表示不排序点击后再判断时升序还是降序text: qsTr(学号) (!stu_id_sort_open ?qsTr(↕) :(stu_id_sort_state ? qsTr(↓) : qsTr(↑)))anchors.left: table_Text.leftanchors.leftMargin: 150anchors.verticalCenter: table_Text.verticalCenterMouseArea {anchors.fill: parentpropagateComposedEvents: trueonPressed: {console.log(student id clicked)studentInfoView.updateSort(stu_id_sort_state ? 1 : 2) // 通知C修改排序方式stu_id_sort_state !stu_id_sort_statestu_id_sort_open true}}}TextShow {id: sex_texttext: qsTr(性别)anchors.left: table_Text.leftanchors.leftMargin: 220anchors.verticalCenter: table_Text.verticalCenter}TextShow {id: age_texttext: qsTr(年龄)anchors.left: table_Text.leftanchors.leftMargin: 290anchors.verticalCenter: table_Text.verticalCenterMouseArea {anchors.fill: parentpropagateComposedEvents: trueonPressed: {console.log(student age clicked)studentInfoView.updateSort(3)stu_id_sort_open false}}}LongLine {anchors.top: table_Text.bottom}}}//listViewRectangle {width: parent.widthheight: parent.height - table_Head.heightcolor: greenanchors.top: table_Head.bottomListView {id: list_viewanchors.rightMargin: 10anchors.bottomMargin: 50anchors.leftMargin: 0anchors.topMargin: 0anchors.fill: parentmaximumFlickVelocity: 800clip: truedelegate: studentInfoDelegatemodel: studentInfoModelboundsBehavior: Flickable.StopAtBoundshighlightMoveDuration: 0ScrollBar.vertical: ScrollBar {id: scrollbar//visible: (current_numbers 8)visible: trueanchors.right: list_view.rightwidth: 8active: truebackground: Item {Rectangle {anchors.right: parent.rightheight: parent.heightcolor: yellowradius: 4}}contentItem: Rectangle {radius: 4color: red}}}//studentInfoDelegate 渲染每一个itemComponent {id: studentInfoDelegateRectangle {id: list_itemwidth: parent.widthheight: 46color: greenRectangle {width: parent.widthheight: parent.heightcolor: greenanchors.verticalCenter: parent.verticalCenterRectangle {id: rect_itemcolor: #333333height: 45TextShow {id: stu_nametext: model.stuNameanchors.verticalCenter: rect_item.verticalCenteranchors.left: rect_item.leftanchors.leftMargin: 68}TextShow {id: id_typetext: model.stuIdanchors.verticalCenter: rect_item.verticalCenteranchors.left: rect_item.leftanchors.leftMargin: 150}TextShow {id: sex_typetext: (model.sex 1) ? qsTr(男) : qsTr(女)anchors.verticalCenter: rect_item.verticalCenteranchors.left: rect_item.leftanchors.leftMargin: 220}TextShow {id: age_typetext: model.age qsTr( 岁)anchors.verticalCenter: rect_item.verticalCenteranchors.left: rect_item.leftanchors.leftMargin: 290}}LongLine {anchors.top: rect_item.bottom}}}}}Component.onCompleted: {// qml加载完成后可以获取C中数据的个数用来标识是否需要展示滚动条current_numbers 4}
}