3

我正在对我的班级进行非常简短(和部分)的描述,以显示我的问题。基本上我已经设置了两个属性。

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)
}

在我的 QML 中,如果我访问该price属性,它工作得很好。但是,如果我访问fruit显然返回的属性,Fruit然后尝试使用它的price属性,那是行不通的。这不应该以这种方式工作吗?

Text {
    id: myText
    anchors.centerIn: parent
    text: basket.price // shows correctly
    //text: basket.fruit.price // doesn't show
}

第二个返回Fruit它也是一个属性并且它具有price属性但它似乎没有访问该属性?这应该工作吗?

更新

我包括我的源代码。我用 新建了一个演示HardwareComponent,这样更有意义。我试图根据收到的答案使其工作,但没有运气。

HardwareComponentclass 是 和 的基ComputerCPU

主文件

#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"

main.qml

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
    }
}

这是我所有项目文件的完整源代码。

当我运行它时,我得到这个输出:

启动 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: computer is not defined

即使它在第 20 行 (computer.price) 行发出警告,它仍然有效并显示计算机的价格 (=500)。如果更改它computer.cpu.price,则会报告相同的警告,但不再显示价格 - 它似乎不起作用。

问题是由于价格是一种虚拟财产,它有效!但是如果我在计算机组件内的另一个硬件组件上使用此属性,它就不起作用!Mido 发布的代码/答案让我希望有一个解决方案,它看起来非常接近!我希望我能完成这项工作。

4

2 回答 2

5

有几件事是错误的,具体与 QML 相关:

  1. 必须在引擎加载 qml 文件之前设置上下文属性。

  2. 您尚未注册该HardwareComponent类型。有关更多信息,请参阅从 C++ 定义 QML 类型。

除了 QML 方面,您似乎希望硬件是具有树结构的组合。由于 aQObject已经是一个组合,您可以利用它来发挥自己的优势。硬件项目树可以是对象树。在QObject添加或删除子代时通知父母:因此在添加和删除子代时很容易保持价格最新。

每个组件都有一个unitPrice:这是单独的组件的价格。price是组件的单价及其子组件的价格的总和。

您可以缓存它并仅在单价变化或子价格变化时更新它,而不是遍历整个树来获取总价格。类似地,当前 CPU 可以被缓存,您可以在任何给定时间强制使用单个 CPU,等等。该示例是功能性的,但只是一个最小的草图。

我还展示了如何更改计算机中的 CPU 类型。价格变化和 CPU 变化都有通知。QML UI 会在cpu属性更改以及任何price属性更改时做出适当的反应。

示例截图

主文件

#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"

main.qml

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) }
        }
    }
}
于 2015-07-20T15:02:40.360 回答
2

Fruit在你的例子中创建了一个类,它工作正常。我创建了一个新实例,Fruit并且可以获得该price值。这是我的代码:

水果.h

#ifndef FRUIT_H
#define FRUIT_H

#include <QObject>
#include <QQuickView>

class Fruit : public QObject
{
    Q_OBJECT
    Q_PROPERTY( int price READ getPrice WRITE setPrice  NOTIFY priceChanged)
    Q_PROPERTY(Fruit * fruit READ fruit WRITE setFruit NOTIFY fruitChanged)

public:
    Fruit();
    ~Fruit();
    Fruit *fruit();
    void setFruit(Fruit * value);
    int getPrice();
    void setPrice(int value);

signals:
    void fruitChanged();
    void priceChanged(int price);

private:
    int _price;
    Fruit *_fruit;
};

#endif // FRUIT_H

水果.cpp

#include "fruit.h"

Fruit::Fruit() :
    _price(1),_fruit(this)
{
}

Fruit::~Fruit()
{
    if(_fruit)
    {
        delete _fruit;
        _fruit = NULL;
    }
}

Fruit *Fruit::fruit()
{
    //Uncomment this line to test the set
    //_fruit = new Fruit;
    return _fruit;
}

void Fruit::setFruit(Fruit *value)
{
    _fruit = value;
    emit fruitChanged();
}

int Fruit::getPrice()
{
    return _price;
}

void Fruit::setPrice(int value)
{
    _price = value;
    emit priceChanged(_price);
}

主文件

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include "fruit.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQuickView view;
    view.rootContext()->setContextProperty("basket", new Fruit);
    view.setSource(QStringLiteral("qml/main.qml"));
    view.show();
    return app.exec();
}

main.qml

import QtQuick 2.2

Rectangle {
    width:800
    height: 480
    property var obj
    color: "yellow"

    Text{
        text: basket.fruit.price
        font.pixelSize: 20
    }

    Component.onCompleted: {
        basket.price = 20
        console.log(basket.fruit.price)
    }
}
于 2015-07-16T19:43:48.917 回答