文档章节

Qt简单的控件运用及加载qml文件混合编程

蓝栩液枫
 蓝栩液枫
发布于 2017/05/20 09:19
字数 1156
阅读 1.2K
收藏 0

钉钉、微博极速扩容黑科技,点击观看阿里云弹性计算年度发布会!>>>

先看一下效果截图:

mytest.pro  //工程文件

QT       += core gui widgets qml

TARGET = menu_test
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

RESOURCES += \
    images.qrc

OTHER_FILES +=

DISTFILES +=

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMessageBox>
#include <QFile>
#include <QString>
#include <QMenuBar>
#include <QAction>
#include <QMenu>
#include <QToolBar>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QWidget>
#include <QFileDialog>
#include <QToolButton>
#include <QStatusBar>
#include <QLabel>
#include <QDateTime>
#include <QTimer>
#include <QPixmap>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QQmlApplicationEngine>
#include <QIODevice>
#include <iostream>
#include <QTextStream>
#include <QSpacerItem>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QSignalMapper>
using namespace std;

class MainWindow : public QMainWindow
{
    Q_OBJECT

public slots:
    void openFile();
    void myTimeout();
    void loadQml();
    void saveTofile();

signals:

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
private slots:
    void slotColorClick(int i);

private:
    QTextEdit *txtTipComp;
    QVBoxLayout *mainLayout;
    QLabel *label;
    QLabel *lab_pixmap;
    QTimer *timer;
    QGraphicsView* pView;
    QQmlApplicationEngine engine;
    QStringList strlist;
    QSignalMapper signalMapper;
    QLabel *label_color;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"

const static char *lcolor0 = "color:white; background-color:#000000";
const static char *lcolor1 = "color:black; background-color:#ff0000";
const static char *lcolor2 = "color:black; background-color:#00ff00";
const static char *lcolor3 = "color:black; background-color:#00ffff";
const static char *lcolor4 = "color:white; background-color:#0000ff";
const static char *lcolor5 = "color:black; background-color:#ff00ff";
const static char *lcolor6 = "color:black; background-color:#ecae47";
const static char *lcolor7 = "color:black; background-color:#ffff00";

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->resize(500,400);  //初始化窗口大小
   // this->setWindowFlags(Qt::FramelessWindowHint);  //设置不显示标题栏

    QMenu *file=new QMenu("File");

    QList<QAction*>actons;
    QAction *Open=new QAction("Open",NULL);
    Open->setShortcut(tr("Ctrl+O"));
    Open->setIcon(QIcon(":/new/prefix1/res/newCreate.png"));
    QAction *Close=new QAction("Close",NULL);
    actons<<Open<<Close;
    file->addActions(actons);

    file->addSeparator();

    QMenu *edit=new QMenu("Edit");
    QAction * Copy=edit->addAction("Copy");
    QAction * Paste=edit->addAction("Paste");
    QAction * Cut=edit->addAction("Cut");


    QMenu *help=new QMenu("Help");
    help->addAction("About...");

    QMenuBar *menuBar=this->menuBar();
    menuBar->addMenu(file); //menuBar()函数会创建一个菜单栏并返回此菜单菜的指针
    menuBar->addMenu(edit);
    menuBar->addMenu(help);

    QToolBar *toobar=addToolBar("toolbar"); //实例化一个工具栏
    toobar->setFixedHeight(30);
    toobar->addAction(Open);


    mainLayout=new QVBoxLayout;
    QWidget *centralWidget=new QWidget;
    setCentralWidget(centralWidget);
    centralWidget->setLayout(mainLayout);

    strlist<<QString(lcolor0)<<QString(lcolor1)<<QString(lcolor2)
              <<QString(lcolor3)<<QString(lcolor4)<<QString(lcolor5)
             <<QString(lcolor6)<<QString(lcolor7);

    QGridLayout *topLayout=new QGridLayout;

    label_color=new QLabel;
    label_color->setStyleSheet(strlist.at(0));
    label_color->setMinimumSize(63,60);
    topLayout->addWidget(label_color,0,0,2,2);
    for(int i=1;i<7;i++)
    {
        QToolButton *btn=new QToolButton;
        btn->setStyleSheet(strlist.at(i));
        if(i<=3)
        {topLayout->addWidget(btn,0,i+1);}
        else
        {topLayout->addWidget(btn,1,i-2);}

        connect(btn, SIGNAL(clicked()), &signalMapper, SLOT(map()));
        signalMapper.setMapping(btn, i);
    }
    topLayout->addItem(new QSpacerItem(1,1,QSizePolicy::Expanding,QSizePolicy::Minimum),0,5);

    mainLayout->addLayout(topLayout);
    txtTipComp = new QTextEdit(this);

    mainLayout->addWidget(txtTipComp);

    //centralWidget->setContentsMargins(0,0,0,-20);


    QStatusBar *statusbar=statusBar();
    label=new QLabel(statusbar);
    statusbar->setStyleSheet(QString("QStatusBar::item{border: 0px}"));
    statusbar->addPermanentWidget(label);



    lab_pixmap=new QLabel;
    lab_pixmap->setPixmap(QPixmap(":/new/prefix1/res/delete.png"));



    QGraphicsScene* pScene = new QGraphicsScene(this);
    pScene->addWidget(lab_pixmap);

    pView = new QGraphicsView(pScene, this);
    pView->setMaximumSize(45,45);

    pView->setFrameShape(QFrame::NoFrame);
    pView->setStyleSheet("background-color:transparent"); //设置背景透明
    statusbar->addWidget(pView);


    timer=new QTimer();
    timer->setInterval(200);
    timer->start();
    connect(timer, SIGNAL(timeout()), this,SLOT(myTimeout()));
    connect(file->addAction("Qml"), SIGNAL(triggered()), this, SLOT(loadQml()));
    connect(Open, SIGNAL(triggered()), this, SLOT(openFile()));
    connect(file->addAction("Save"),SIGNAL(triggered()),this,SLOT(saveTofile()));
    connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotColorClick(int)));
}

MainWindow::~MainWindow()
{

}

void MainWindow::slotColorClick(int i)
{
    label_color->setStyleSheet(strlist.at(i));
}

void MainWindow::openFile()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("open the file"),"../", tr("Text files (*.txt);;Images (*.png *.xpm *.jpg);;XML files (*.xml)"));

    if (filename.isEmpty()) return;

    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        cout<< "Open failed." << endl;
        return;
    }

    QTextStream txtInput(&file);
    QString lineStr;
    while(!txtInput.atEnd())
    {
        lineStr += txtInput.readLine()+"\n";

    }
    txtTipComp->setText(lineStr);
    txtTipComp->update();

    file.close();

}

void MainWindow::myTimeout()
{
    QDateTime time=QDateTime::currentDateTime();
    label->setText(time.toString("yyyy-MM-dd  hh:mm:ss  ddd"));
    pView->rotate(30);
    label->update();
    pView->update();
}

void MainWindow::loadQml()
{

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

}

void MainWindow::saveTofile()
{
    QString string=txtTipComp->toPlainText();

    QString filename = QFileDialog::getSaveFileName(this, tr("open the file"),"../", tr("Text files (*.txt);;Images (*.png *.xpm *.jpg);;XML files (*.xml)"));

    if (filename.isEmpty()) return;

    QFile file(filename);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        cout << "Open failed." << endl;
        return;
    }

    QTextStream txtOutput(&file);
    txtOutput << string;
    file.close();
}

main.cpp

#include <QApplication>
#include "mainwindow.h"


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

main.qml

import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import Qt.labs.folderlistmodel 2.1
import QtQuick.Controls.Styles 1.4

Window {
    id:wnd1
    visible: true
    width: 500
    height: 400

    Rectangle{
        width: 50
        height: 40
        color: "red"
        x:40
        y:40
    }

    Loader{
        id:pageLoader
        x:200
    }

    function changePage() {
        pageLoader.source = "qrc:/color.qml"
        console.log("call changePage");
    }

    Button{
        text: "打开"
        x:100
        y:100
        width:100
        height:40
        style: ButtonStyle
        {
            label: Text
            {
                anchors.centerIn: parent
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
                width:80
                text: control.text
                font.family:"楷体"
                font.pointSize: 10
            }
        }
        onClicked:changePage();
    }

    Item {
        id: name
        x:300
        y:300

        Rectangle{
            id:rect1
            width: 30
            height: 30
            color: "blue"
        }
        Rectangle{
            id:rect2
            width: rect1.width*2
            height: rect1.height
            color:"yellow"
            x:rect1.x+rect1.width
        }

    }

}

cell.qml

import QtQuick 2.0

Item {
    id: container
        property alias cellColor: rectangle.color
        signal clicked(color cellColor)

        width: 40; height: 25

        Rectangle {
            id: rectangle
            border.color: "white"
            anchors.fill: parent
        }

        MouseArea {
            anchors.fill: parent
            onClicked: container.clicked(container.cellColor)
        }
}

color.qml

import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import Qt.labs.folderlistmodel 2.1
import QtQuick.Controls.Styles 1.4
import QtQuick 2.4

Window {   //如果不指定是window窗口,则此文件的内容会嵌入到加载器所在的位置
    id:wnd2
    visible: true
    width: 500
    height: 400
    Item {
        id: name
        Column{
            Row{
                id:row1
                Rectangle{id:rect1;height: 50;width: 50;color:"green"}
                Rectangle{id:rect2;height: 50;width: 50;color:"blue"}
            }
            Row{
                id:row2
                Rectangle{id:rect3;height: 50;width: 50;color:"red"}
                Rectangle{id:rect4;height: 50;width: 50;color:"yellow"}
            }


            Rectangle{
                id:page
                width:300;height:200
                color:"lightgray"
                Text{
                    id:helloText
                    text:"Hello world!"
                    y:30
                 anchors.horizontalCenter:page.horizontalCenter
                 font.pointSize:24;font.bold: true
                }
                Grid{
                    id:colorPicker
                    x:4;anchors.bottom:page.bottom;anchors.bottomMargin: 4
                    rows:2;columns: 3;spacing: 3
                    Cell {cellColor:"red";onClicked:helloText.color=cellColor}
                    Cell { cellColor: "red"; onClicked: helloText.color = cellColor }
                    Cell { cellColor: "green"; onClicked: helloText.color = cellColor }
                    Cell { cellColor: "blue"; onClicked: helloText.color = cellColor }
                    Cell { cellColor: "yellow"; onClicked: helloText.color = cellColor }
                    Cell { cellColor: "steelblue"; onClicked: helloText.color = cellColor }
                    Cell { cellColor: "black"; onClicked: helloText.color = cellColor }
                }
            }
        }
    }
}

 

蓝栩液枫
粉丝 5
博文 41
码字总数 37535
作品 0
深圳
程序员
私信 提问
加载中
请先登录后再评论。
QML基础之窗体构建与代码介绍

1 什么是Qt Qucik? Qt Quick是QtSDK4.7中引入的一种新的界面开发框架,使用QtQuick,你可以快速、 轻松地创建供移动和嵌入式设备使用的动态触摸式界面和轻最级应用程序,这也是它被命名 为Qui...

osc_2y1ylz6c
04/28
9
0
QML-WebEngineView加载html(Echarts绘图)

实现QML中运用webEngineView加载Echarts GitHub:八至 作者:狐狸家的鱼 本文链接:QML-WebEngineView加载Echarts 一、前言 Qt允许使用混合GUI创建应用程序,甚至支持通过webChannel和webSock...

osc_lit0zkpv
2018/11/28
4
0
QML官方文档:Qt Quick Controls 1和2对比

Qt Quick Controls有1和2两个版本,在程序中会看到好多1和2版本混合使用的情况。 原文:https://doc.qt.io/qt-5/qtquickcontrols2-differences.html 参考:QtQuick.Controls 2与 QtQuick.Co...

osc_taqquicm
2019/08/07
4
0
Qt文档阅读笔记-QQmlApplicationEngine解析与实例(qml与C++混合编程及QQuick与widgets混合)

目录 官方解析 博主例子 官方解析 QQmlApplicationEngine提供了从一个QML文件里面加载应用程序的方式。 这类联合了QQmlEngine和QmlComponent去加载单独的QML文件。他还向QML提供了应用程序的...

抖音hzcya
06/25
2
0
Qt5开发实战pdf

下载地址:网盘下载 内容简介 · · · · · · Qt支持C++、Python、Ruby、Perl等多种编程语言,常规用户应用程序、多媒体、后端系统管理、汽车、国防、家电、移动设备等多个领域都在广泛应...

osc_xyoic19y
2018/02/09
3
0

没有更多内容

加载失败,请刷新页面

加载更多

技术教程| 百度鹰眼历史轨迹查询:轨迹抽稀功能

本文作者:用****9 本篇教程中,我们将详细地说明鹰眼历史轨迹查询(gettrack接口)中,如何通过vacuate_grade选项对轨迹进行抽稀,以及不同的抽稀力度对轨迹产生的影响。 上一篇教程中,我们...

百度开发者中心
前天
0
0
整数的最大值和最小值 - Maximum and Minimum values for ints

问题: I am looking for minimum and maximum values for integers in python. 我在python中寻找整数的最小值和最大值。 For eg., in Java, we have Integer.MIN_VALUE and Integer.MAX_VA......

法国红酒甜
15分钟前
16
0
Quartz的Misfire处理规则 错过任务执行时间的处理机制

调度(scheduleJob)或恢复调度(resumeTrigger,resumeJob)后不同的misfire对应的处理规则 CronTrigger withMisfireHandlingInstructionDoNothing ——不触发立即执行 ——等待下次Cron触发频率...

独钓渔
今天
4
0
如何在Django视图中合并两个或多个查询集? - How to combine two or more querysets in a Django view?

问题: I am trying to build the search for a Django site I am building, and in that search, I am searching in 3 different models. 我正在尝试搜索要构建的Django网站,在该搜索中,我......

javail
今天
5
0
PHP解析/语法错误; 以及如何解决它们? - PHP parse/syntax errors; and how to solve them?

问题: Everyone runs into syntax errors. 每个人都遇到语法错误。 Even experienced programmers make typos. 即使是经验丰富的程序员也会打错字。 For newcomers, it's just part of the......

fyin1314
今天
20
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部