In this example, I'm writting the "stylesheet" on a QTextEdit
and applying it to the QMainWindow
myStruct.a: 10;
myStruct.b: "hello world";
setStyleSheet(textEdit->toPlainText());
I tried to follow this question: https://forum.qt.io/topic/82325/best-way-to-access-a-cpp-structure-in-qml/6
But none of the functions is being called setA
getA
getMyStruct
or setMyStruct
when the stylesheet is applied.
What the proper way to update the values of MyStruct
using the stylesheet?
struct MyStruct
{
Q_GADGET
int m_a;
QString m_b;
Q_PROPERTY(int a READ getA WRITE setA)
Q_PROPERTY(QString b MEMBER m_b)
void setA(int a)
{
m_a = a;
}
int getA() const
{
return m_a;
}
};
Q_DECLARE_METATYPE(MyStruct)
class MainWindow : public QMainWindow
{
Q_OBJECT
Q_PROPERTY(MyStruct myStruct READ getMyStruct WRITE setMyStruct NOTIFY myStructChanged)
public:
MainWindow() : QMainWindow(nullptr), ui(new Ui::MainWindow())
{
ui->setupUi(this);
QVBoxLayout* layout = new QVBoxLayout();
ui->centralWidget->setLayout(layout);
QTextEdit* textEdit = new QTextEdit(this);
textEdit->setText(R"(
myStruct.a: 10;
myStruct.b: "hello world";
)");
QPushButton* button = new QPushButton("update", this);
connect(button, &QPushButton::clicked, [=]
{
setStyleSheet(textEdit->toPlainText());
});
layout->addWidget(textEdit);
layout->addWidget(button);
}
MyStruct myStruct;
MyStruct getMyStruct() const
{
return myStruct;
}
void setMyStruct(MyStruct val)
{
myStruct = val;
emit myStructChanged();
}
void changeEvent(QEvent* event)
{
if (event->type() == QEvent::StyleChange)
{
qDebug() << "style changed";
}
}
signals:
void myStructChanged();
private:
Ui::MainWindow* ui;
};