【发布时间】:2019-06-04 16:41:21
【问题描述】:
我目前正在使用Qt 5.7,并且我已将QPushButton 子类化为在QML side 上使用Qt Style sheets 的基本思想。这是头文件:
#ifndef LTPUSHBUTTON_H
#define LTPUSHBUTTON_H
#include <QWidget>
#include <QPushButton>
#include <QString>
/**
* @class Modified push button class
*/
class LtPushButton : public QPushButton
{
Q_OBJECT
public:
/**
* @brief Constructor
* @param parent
*/
LtPushButton(const QString& ltText=QString(),
QWidget* const parent=Q_NULLPTR);
/**
* @brief Method for settings CSS style from QML side
* @param ltCSSStyle
*/
Q_INVOKABLE void ltSetCSSStyle(const QString& ltCSSStyle);
};
#endif // LTPUSHBUTTON_H
及其实现:
#include "ltpushbutton.h"
LtPushButton::LtPushButton(const QString <Text,
QWidget* const parent)
: QPushButton(parent)
{
this->setText(ltText);
} // constructor
void LtPushButton::ltSetCSSStyle(const QString& ltCSSStyle)
{
this->setStyleSheet(ltCSSStyle);
} // ltSetCSSStyle
LtPushButton 类型在 main.cpp 中注册:
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlEngine>
#include "ltpushbutton.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<LtPushButton>("com.testapp.gui",
1,
0,
"LtPushButton");
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
当我尝试在main.qml 中设置窗口样式表时:
import QtQuick 2.7
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
import com.testapp.gui 1.0
Window
{
width: 640
height: 480
visible: true
title: qsTr("Hello World")
color: "red"
GridLayout
{
anchors.fill: parent
rows: 2
columns: 2
LtPushButton
{
id: ltUpperLeftButton
Layout.fillWidth: true
Layout.fillHeight: true
Layout.alignment: Qt.AlignHCenter|Qt.AlignVCenter
text: qsTr("One");
} // LtPushButton
Component.onCompleted:
{
ltUpperLeftButton.ltSetCSSStyle("border-top-left-radius: 20px;
border-top-right-radius: 20px;
border-bottom-left-radius: 20px;
border-bottom-right-radius: 20px;
background-color: #0047bd;
border: 2px solid #0047bd;
color: #ffffff;
outline: none;");
} // Component.onCompleted
} // GridLayout
} // Window
应用程序崩溃。基本上,我试图用任意数量的径向角实现QML Button,例如,右下角是径向角,其他角是垂直的:
或左下角是径向拐角,其他角是垂直的:
同样适用于上角。
【问题讨论】:
-
好吧,你不能。 QML 中的绘画系统与 QtWidgets 不同,除了 QPushButton 期望 QWidget 作为父级,但在 QML 中它指出父级是 GridLayout 而不是 QWidget。您可以使用 QQuickWidgets 在 QWidget 中嵌入 QML,但反之则不行
-
您对 2 个不兼容的概念感到困惑。 QtQuick 在 QPushButton 为 QtWidgets 时使用Scene Graph