我想为我的Qt Quick Controls设计一个自定义设计。例如,我想改变工具栏的背景颜色,因为我讨厌默认设计。我怎么能这样做?
答案 0 :(得分:6)
在Qt快速控制中,limited styling available通过Qt快速控制样式项目,如ButtonStyle
,CheckBoxStyle
等。
目前,其他风格需要深入研究Qt sources并弄乱内部细节。
以下是如何修改工具栏样式的完整示例。
main.qml
import QtQuick 2.1
import QtQuick.Layouts 1.0
import QtQuick.Controls 1.0
ApplicationWindow {
toolBar: ToolBar {
id: toolbar
Component.onCompleted: toolbar.data[0].item.children = [newRectangle];
property Item _newRectangle: Rectangle {
// The rectangle within the ToolBarStyle's panel
// Gleaned from:
// http://qt.gitorious.org/qt/qtquickcontrols/source/
// c304d741a27b5822a35d1fb83f8f5e65719907ce:src/styles/Base/ToolBarStyle.qml
id: newRectangle
anchors.fill: parent
gradient: Gradient{
GradientStop{color: "#a00" ; position: 0}
GradientStop{color: "#aaa" ; position: 1}
}
Rectangle {
anchors.bottom: parent.bottom
width: parent.width
height: 1
color: "#999"
}
}
RowLayout {
ToolButton { iconSource: "image://images/img1" }
ToolButton { iconSource: "image://images/img2" }
}
}
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickWindow>
#include <QImage>
#include <QPainter>
#include <QQuickImageProvider>
#include <QDebug>
class ImageProvider : public QQuickImageProvider
{
public:
ImageProvider() : QQuickImageProvider(QQuickImageProvider::Image) {}
QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) {
QImage img(32, 32, QImage::Format_ARGB32_Premultiplied);
img.fill(0); // transparent
QPainter p(&img);
p.setRenderHint(QPainter::Antialiasing);
p.translate(16, 16);
p.scale(14, 14);
p.setPen(QPen(Qt::black, 0.1));
if (id == "img1") {
p.drawEllipse(QPointF(0, 0), 1, 1);
}
else if (id == "img2") {
p.drawLine(-1, -1, 1, 1);
p.drawLine(-1, 1, 1, -1);
}
*size = img.size();
return img;
}
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.addImageProvider("images", new ImageProvider);
engine.load(QUrl("qrc:///main.qml"));
QObject *topLevel = engine.rootObjects().value(0);
QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
window->show();
return app.exec();
}
main.qrc
<RCC>
<qresource prefix="/">
<file>main.qml</file>
</qresource>
</RCC>
答案 1 :(得分:1)
我认为以下几行完全没用:
QObject *topLevel = engine.rootObjects().value(0);
QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
window->show();
您只需要执行以下操作:
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();