我们知道,在设计中,我们通常需要选择我们所需要的颜色,比如红色,绿色,黄色等.在QML语言中,已经有很多预定义的颜色值,比如"red", "green", "yellow"等.那么我们怎么可以得到有那些预定义的颜色,并知道它们的颜色呢?在今天的这篇文章中,我们来写一个简单的测试应用来显示所有已经被预定义的颜色.
在这里,我们利用了QColors:colorNames() API接口拿到所有的颜色的名称.
在这个QML文件中,我们把我们拿到的颜色名称,通过列表的方式进行显示.同时也显示出它的颜色:
我们知道在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
}
}
}
}
}
以后,如果需要什么样的颜色,我们可以通过这个应用找到相应的颜色,从而我们知道这个颜色的具体的名称.当然,我们也可以使用像诸如#RRGGBB这样的颜色定义在我们的应用中.