本文介绍了自定义样式 Qt 快速控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为我的 Qt Quick Controls 进行自定义设计.例如,我想更改工具栏的背景颜色,因为我讨厌默认设计.我该怎么做?
I would like to have a custom design for my Qt Quick Controls. For example, I would like to change background colour of a tool bar, since I hate the default design. How can I do that?
推荐答案
在Qt Quick Controls中,有有限样式可用 通过 Qt 快速控制样式项目,如 ButtonStyle
、CheckBoxStyle
等.
In Qt Quick Controls, there is limited styling available via Qt Quick Control Styles items, like ButtonStyle
, CheckBoxStyle
, etc.
目前,其他样式需要深入研究 Qt 源代码 并搞乱内部细节.
At the moment, other styles require delving into Qt sources and messing with internal details.
这是一个如何修改工具栏样式的完整示例.
Here is a complete example of how one might modify the toolbar's style.
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>
这篇关于自定义样式 Qt 快速控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!