Qt简单的控件运用及加载qml文件混合编程
Qt简单的控件运用及加载qml文件混合编程
蓝栩液枫 发表于7个月前
Qt简单的控件运用及加载qml文件混合编程
  • 发表于 7个月前
  • 阅读 24
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

摘要: 添加菜单,动作,快捷键,工具栏,状态栏,系统时间,旋转label,控件边框去除,背影透明,计时器,信号槽,信号映射,layout布局,文件操作,qml文件的加载等的一些用法示例。。。

先看一下效果截图:

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 }
                }
            }
        }
    }
}

 

标签: qt 图片旋转
共有 人打赏支持
粉丝 2
博文 21
码字总数 12790
×
蓝栩液枫
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: