【问题标题】:Add QObject in the combo box of Qt在Qt的组合框中添加QObject
【发布时间】:2009-10-19 03:53:03
【问题描述】:

我创建了一个自定义类,比如 MyClass。现在如何在下面的组合框中添加对 MyClass 的引用作为第二个参数的引用:

this->ui->comboBox->addItem("item-1", );

目的是当项目更改甚至被触发时,我想获取 MyClass 的特定类实例并相应地进行处理。

【问题讨论】:

    标签: qt qcombobox qobject


    【解决方案1】:

    首先需要使用Q_DECLARE_METATYPE(MyClass*),这样才能在QVariant中使用类型。然后你可以像这样添加项目:

    this->ui->comboBox->addItem("item-1", QVariant::fromValue(myClass));
    

    然后拿回来:

    this->ui->combobox->itemData(x).value<MyClass*>();
    

    【讨论】:

      【解决方案2】:

      以上答案语法略有错误,

      在MyClass头文件中使用Q_DECLARE_METATYPE(MyClass*),这样该类型就可以在QVariant中使用了。

      像这样添加项目:

      this->ui->comboBox->addItem("item-1", QVariant::fromValue(myClass));

      然后把它拿回来: this->ui->combobox->itemData(x).value();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-06
        • 2016-09-13
        • 1970-01-01
        • 2020-10-29
        • 2013-01-27
        • 2015-08-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多