zar*_*zar 6 qt qml qtquick2 qproperty
我对我的班级进行了非常简短(和部分)的描述,以表明我的问题。基本上我设置了两个属性。
class Fruit : public QObject
{
Q_OBJECT
....
public:
Q_PROPERTY( int price READ getPrice NOTIFY priceChanged)
Q_PROPERTY(Fruit * fruit READ fruit WRITE setFruit NOTIFY fruitChanged)
}
Run Code Online (Sandbox Code Playgroud)
在我的 QML 中,如果我访问该price属性,它会运行良好。但是,如果我访问fruit明显返回的属性Fruit,然后尝试使用它的price属性,那是行不通的。这不应该这样工作吗?
Text {
id: myText
anchors.centerIn: parent
text: basket.price // shows correctly
//text: basket.fruit.price // doesn't show
}
Run Code Online (Sandbox Code Playgroud)
第二个返回的Fruit也是一个属性,它有price属性,但它似乎无法访问该属性?这应该有效吗?
更新
我包括我的源代码。我用 创建了一个新的演示HardwareComponent,这样更有意义。我试图根据我收到的答案让它工作,但没有运气。
HardwareComponentComputerclass 是和的基类CPU。
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
class HardwareComponent : public QObject
{
Q_OBJECT
public:
HardwareComponent() : m_price(0) {}
virtual int price() = 0;
virtual Q_INVOKABLE void add(HardwareComponent * item) { m_CPU = item; }
HardwareComponent * getCPU() const { return m_CPU; }
Q_SLOT virtual void setPrice(int arg)
{
if (m_price == arg) return;
m_price = arg;
emit priceChanged(arg);
}
Q_SIGNAL void priceChanged(int arg);
protected:
Q_PROPERTY(HardwareComponent * cpu READ getCPU);
Q_PROPERTY(int price READ price WRITE setPrice NOTIFY priceChanged)
HardwareComponent * m_CPU;
int m_price;
};
class Computer : public HardwareComponent
{
Q_OBJECT
public:
Computer() { m_price = 500; }
int price() { return m_price; }
void setprice(int arg) { m_price = arg; }
};
class CPU : public HardwareComponent
{
Q_OBJECT
public:
CPU() { m_price = 100; }
int price() { return m_price; }
void setprice(int arg) { m_price = arg; }
};
int main(int argc, char *argv[])
{
HardwareComponent * computer = new Computer;
CPU * cpu = new CPU;
computer->add( cpu );
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
engine.rootContext()->setContextProperty("computer", computer);
return app.exec();
}
#include "main.moc"
Run Code Online (Sandbox Code Playgroud)
import QtQuick 2.3
import QtQuick.Window 2.2
Window {
visible: true
width: 360
height: 360
Text {
anchors.centerIn: parent
text: computer.price // works
//text: computer.cpu.price // doesn't work, doesn't show any value
}
}
Run Code Online (Sandbox Code Playgroud)
这是我所有项目文件的完整源代码。
当我运行它时,我得到以下输出:
启动 C:\Users\User\Documents\My Qt Projects\build-hardware-Desktop_Qt_5_4_0_MSVC2010_OpenGL_32bit-Debug\debug\hardware.exe...启用 QML 调试。仅在安全的环境中使用此功能。qrc:/MainForm.ui.qml:20: ReferenceError: 计算机未定义
尽管它在第 20 行 (computer.price) 行发出警告,但它仍然有效并显示计算机的价格 (=500)。如果更改它computer.cpu.price,则会报告相同的警告,但价格不再显示 - 它似乎不起作用。
问题是,由于价格是虚拟财产,所以它有效!但如果我在计算机组件内的另一个硬件组件上使用此属性,它就不起作用!Mido 发布的代码/答案让我希望有一个解决方案,它看起来非常接近!我希望我能完成这项工作。
只有一些问题,特别是与 QML 相关的问题:
必须在引擎加载 qml 文件之前设置上下文属性。
您尚未注册该HardwareComponent类型。有关更多信息,请参阅从 C++ 定义 QML 类型。
除了 QML 方面之外,您似乎还希望硬件成为具有树结构的复合体。由于 aQObject已经是复合材料,因此您可以利用它来发挥自己的优势。硬件项树可以是对象树。QObject添加或删除子项时会通知家长:因此,在添加和删除子项时可以轻松保持最新价格。
每个组件都有一个unitPrice:这是单独组件的价格。这price是组件的单价及其子组件的价格总和。
您可以缓存它并仅在单价更改或子价格更改时更新它,而不是遍历整个树来获取总价。同样,当前的 CPU 可以被缓存,您可以在任何给定时间强制使用单个 CPU,等等。该示例是功能性的,但只是一个最小的草图。
我还展示了如何更改计算机中的 CPU 类型。价格变化和 CPU 变化都会有通知。cpu当属性更改以及任何price属性更改时, QML UI 都会做出适当的反应。

#include <QGuiApplication>
#include <QtQml>
class HardwareComponent : public QObject {
Q_OBJECT
Q_PROPERTY(QString category MEMBER m_category READ category CONSTANT)
Q_PROPERTY(HardwareComponent * cpu READ cpu WRITE setCpu NOTIFY cpuChanged)
Q_PROPERTY(int price READ price NOTIFY priceChanged)
Q_PROPERTY(int unitPrice MEMBER m_unitPrice READ unitPrice WRITE setUnitPrice NOTIFY unitPriceChanged)
QString m_category;
int m_unitPrice;
bool event(QEvent * ev) Q_DECL_OVERRIDE {
if (ev->type() != QEvent::ChildAdded && ev->type() != QEvent::ChildRemoved)
return QObject::event(ev);
auto childEvent = static_cast<QChildEvent*>(ev);
auto child = qobject_cast<HardwareComponent*>(childEvent->child());
if (! child) return QObject::event(ev);
if (childEvent->added())
connect(child, &HardwareComponent::priceChanged,
this, &HardwareComponent::priceChanged, Qt::UniqueConnection);
else
disconnect(child, &HardwareComponent::priceChanged,
this, &HardwareComponent::priceChanged);
emit priceChanged(price());
if (child->category() == "CPU") emit cpuChanged(cpu());
return QObject::event(ev);
}
public:
HardwareComponent(int price, QString category = QString(), QObject * parent = 0) :
QObject(parent), m_category(category), m_unitPrice(price) {}
HardwareComponent * cpu() const {
for (auto child : findChildren<HardwareComponent*>())
if (child->category() == "CPU") return child;
return 0;
}
Q_INVOKABLE void setCpu(HardwareComponent * newCpu) {
Q_ASSERT(!newCpu || newCpu->category() == "CPU");
auto oldCpu = cpu();
if (oldCpu == newCpu) return;
if (oldCpu) oldCpu->setParent(0);
if (newCpu) newCpu->setParent(this);
emit cpuChanged(newCpu);
}
Q_SIGNAL void cpuChanged(HardwareComponent *);
virtual int price() const {
int total = unitPrice();
for (auto child : findChildren<HardwareComponent*>(QString(), Qt::FindDirectChildrenOnly))
total += child->price();
return total;
}
Q_SIGNAL void priceChanged(int);
int unitPrice() const { return m_unitPrice; }
void setUnitPrice(int unitPrice) {
if (m_unitPrice == unitPrice) return;
m_unitPrice = unitPrice;
emit unitPriceChanged(m_unitPrice);
emit priceChanged(this->price());
}
Q_SIGNAL void unitPriceChanged(int);
QString category() const { return m_category; }
};
struct Computer : public HardwareComponent {
Computer() : HardwareComponent(400) {}
};
class FluctuatingPriceComponent : public HardwareComponent {
QTimer m_timer;
int m_basePrice;
public:
FluctuatingPriceComponent(int basePrice, const QString & category = QString(), QObject * parent = 0) :
HardwareComponent(basePrice, category, parent),
m_basePrice(basePrice) {
m_timer.start(250);
connect(&m_timer, &QTimer::timeout, [this]{
setUnitPrice(m_basePrice + qrand()*20.0/RAND_MAX - 10);
});
}
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
Computer computer;
HardwareComponent memoryBay(40, "Memory Bay", &computer);
HardwareComponent memoryStick(60, "Memory Stick", &memoryBay);
FluctuatingPriceComponent cpu1(100, "CPU", &computer);
HardwareComponent cpu2(200, "CPU");
qmlRegisterUncreatableType<HardwareComponent>("bar.foo", 1, 0, "HardwareComponent", "");
engine.rootContext()->setContextProperty("computer", &computer);
engine.rootContext()->setContextProperty("cpu1", &cpu1);
engine.rootContext()->setContextProperty("cpu2", &cpu2);
engine.load(QUrl("qrc:/main.qml"));
return app.exec();
}
#include "main.moc"
Run Code Online (Sandbox Code Playgroud)
import QtQuick 2.0
import QtQuick.Controls 1.2
import QtQuick.Window 2.0
Window {
visible: true
Column {
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
Text {
text: "Computer price: " + computer.price
}
Text {
text: "CPU price: " + (computer.cpu ? computer.cpu.price : "N/A")
}
Button {
text: "Use CPU 1";
onClicked: { computer.setCpu(cpu1) }
}
Button {
text: "Use CPU 2";
onClicked: { computer.setCpu(cpu2) }
}
Button {
text: "Use no CPU";
onClicked: { computer.setCpu(undefined) }
}
}
}
Run Code Online (Sandbox Code Playgroud)