QML语言中的颜色

185 篇文章 6 订阅
159 篇文章 2 订阅
我们知道,在设计中,我们通常需要选择我们所需要的颜色,比如红色,绿色,黄色等.在QML语言中,已经有很多预定义的颜色值,比如"red", "green", "yellow"等.那么我们怎么可以得到有那些预定义的颜色,并知道它们的颜色呢?在今天的这篇文章中,我们来写一个简单的测试应用来显示所有已经被预定义的颜色.


我们知道在Qt API中,有一个API叫做QColor.在它的里面有一个方法叫做:

QStringList colorNames()

显然,我们可以利用这个API来得到所有的颜色值.当然,我们也可以从文件中看到所有的已经定义的颜色值.

为了更加清楚地看到Qt已经为我们定义好的颜色,我们特别做了一个应用.


main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    // Lets get the color names
    QStringList colors = QColor::colorNames();

    QQuickView view;
    view.rootContext()->setContextProperty("colors", QVariant::fromValue(colors));
    view.setSource(QUrl(QStringLiteral("qrc:///Main.qml")));
    view.setResizeMode(QQuickView::SizeRootObjectToView);

    view.show();
    return app.exec();
}

在这里,我们利用了QColors:colorNames() API接口拿到所有的颜色的名称.

Main.qml


import QtQuick 2.4
import Ubuntu.Components 1.2

/*!
    \brief MainView with a Label and Button elements.
*/

MainView {
    // objectName for functional testing purposes (autopilot-qt5)
    objectName: "mainView"

    // Note! applicationName needs to match the "name" field of the click manifest
    applicationName: "qmlcolors.liu-xiao-guo"

    /*
     This property enables the application to change orientation
     when the device is rotated. The default is false.
    */
    //automaticOrientation: true

    // Removes the old toolbar and enables new features of the new header.
    //    useDeprecatedToolbar: false

    width: units.gu(60)
    height: units.gu(85)

    Page {
        title: i18n.tr("qmlcolors")

        ListView {
            anchors.fill: parent
            model: colors
            delegate: Item {
                width: parent.width
                height: units.gu(5)

                Label {
                    text: modelData
                    fontSize: "large"
                    anchors.left: parent.left
                    anchors.leftMargin: units.gu(1)
                    anchors.verticalCenter: parent.verticalCenter
                }

                Rectangle {
                    anchors.right: parent.right
                    height: parent.height
                    width: parent.width *.7
                    color: modelData
                }
            }
        }
    }
}

在这个QML文件中,我们把我们拿到的颜色名称,通过列表的方式进行显示.同时也显示出它的颜色:

  

以后,如果需要什么样的颜色,我们可以通过这个应用找到相应的颜色,从而我们知道这个颜色的具体的名称.当然,我们也可以使用像诸如#RRGGBB这样的颜色定义在我们的应用中.

整个项目的源码在地址: https://github.com/liu-xiao-guo/qmlcolors


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值