[Qt-interest] Using typedef'ed custom type as Q_PROPERTY

Andras Toth parrotfortytwo at gmail.com
Thu Aug 27 16:06:52 CEST 2009


Hello, I have been trying all day to use a typedef'ed custom variable
as Q_PROPERTY, however, it seems impossible to read and write this
value through methods property(const char*) and setProperty(const
char*, const QVariant &)

Below is an example (also available at: http://pastebin.ca/1544643)

/*
cat.h
*/

typedef int ID;
Q_DECLARE_METATYPE(ID);

class Cat : public QObject
{
    Q_OBJECT
    Q_PROPERTY(ID id READ getId WRITE setId);
public:
    Cat();
    ID getId() const;
    void setId(ID id);
protected:
    ID m_id;
};


/*
cat.cpp
*/

Cat::Cat():
        m_id(42)
{
    qRegisterMetaType<ID>("ID");
}

ID Cat::getId() const
{
    return m_id;
}

void Cat::setId(ID id)
{
    m_id = id;
}

/*
mainwindow.cpp
*/

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QVariant var = m_cat.property("id");
    ID id1 = var.value<ID>();
    std::cerr << "id1=" << id1 << std::endl;

    m_cat.setProperty("id", 127);
    QVariant var2 = m_cat.property("id");
    ID id2 = var2.value<ID>();
    std::cerr << "id2=" << id2 << std::endl;

}

/*
output:

id1=0
id2=0
*/

The output here is in both cases 0, whereas it should be 42 in the
first case and 127 in the second. I have tried debugging the program,
and I've seen that getId() is called twice as it should, however
Cat::setId(ID) is never called.
What I already know is the following (because I asked the same
question on irc and people there kindly helped me):

- qRegisterMetaType<ID>("ID") should be called only once, so it's
better to put it in main() rather than the ctor of a class
- QVariant could be constructed esplicitly when passing to
setProperty: m_cat.setProperty("id", QVariant::fromValue<ID>(127)); --
this did not help either

Regards,

Andras



More information about the Qt-interest-old mailing list