【问题标题】:Qt Dynamically create QWidget from QStringQt 从 QString 动态创建 QWidget
【发布时间】:2012-10-15 03:03:27
【问题描述】:

我正在尝试创建一个从数据库读取信息并相应设置布局的程序。具体来说,我想读取两个日期字段,并根据天数之间的差异,创建天数的元素。有没有人知道如何做到这一点?由于明显的原因,我尝试使用 QString->text() 属性创建一个元素但没有成功,我已经设法编写了一个函数来创建一个元素,但我的问题是我无法控制元素的名称,使得以我对 c++ 的垃圾知识,我不可能与给定的元素进行交互。

感谢您的宝贵时间,

干杯。

【问题讨论】:

    标签: c++ qt qwidget qstring


    【解决方案1】:

    我认为QHash 将是满足您需求的完美工具。它允许通过唯一键存储和查找几乎所有内容。这意味着您可以将小部件及其标题作为键存储,然后从该哈希中检索具有特定标题的小部件。

    这里是如何定义这样一个哈希:

    // .h file
    #include <QtCore/QHash>
    #include <QtGui/QWidget>
    
    class MyWidget : public QWidget
    {
        // ...
    private:
        QHash< QString, QWidget* > m_dynamicWidgetHash;
    };
    

    然后可以像这样将小部件(或任何 QWidget 子类)存储在散列中,假设标题始终是唯一的

    // .cpp file
    void MyWidget::someMethod()
    {
        QList< QString > widgetTitles = getWidgetTitlesFromSomewhere();
    
        foreach( QString title, widgetTitles )
        {
            SomeWidgetSubclass* widget = new SomeWidgetSubclass( this );
            widget->setTitle( title );
            // Note: This will not work if two widgets can have the same title
            Q_ASSERT( !m_dynamicWidgetHash.contains( title ) );
            m_dynamicWidgetHash.insert( title, widget );
        }
    }
    

    然后您可以稍后找到您的小部件,只知道这样的名称:

    // .cpp file
    void MyWidget::someOtherMethod( const QString& title )
    {
        SomeWidgetSubclass* widget = m_dynamicWidgetHash.value( title );
        if( !widget )
        {
            // TODO: Error Handling
            return;
        }
    
        // Do whatever you want with the widget here
    }
    

    【讨论】:

    • Qt 在它的文档中隐藏了许多漂亮的东西 ;-) 如果您是新手,我建议您阅读Container Classes
    【解决方案2】:

    另外,您可能会对如何使用QMetaType 按类名创建对象感兴趣。有QMetaType::construct 方法。它要求之前应该调用qRegisterMetaType 函数。详细说明为here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-28
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      相关资源
      最近更新 更多