[英]Qt Dynamically create QWidget from QString
I am trying to create a program that reads information from a database, and accordingly set up the layout. 我正在尝试创建一个从数据库中读取信息的程序,并相应地设置布局。 Specifically, I want to read two date fields and depending on the difference between the days, create a day(s) number of elements.
具体来说,我想读取两个日期字段,并根据日期之间的差异,创建一天的元素数量。 Have anyone got an idea on how this could be done?
谁有人知道如何做到这一点? I have tried to create an element using the QString->text() property with no success for obvious reasons and I have managed to write a function to create an element, but my problem is that I cannot control the name of the element, making it impossible for me with my rubbish knowledge about c++ to then interact with the given element.
我试图使用QString-> text()属性创建一个元素,但由于显而易见的原因没有成功,我设法编写了一个函数来创建一个元素,但我的问题是我无法控制元素的名称,使得对于我来说,我对c ++的垃圾知识不可能与给定的元素进行交互。
Thank you for your time, 感谢您的时间,
Cheers. 干杯。
I think a QHash
would be the perfect tool for your needs. 我认为
QHash
将是满足您需求的完美工具。 It allows storing and lookup of pretty much anything through a unique key. 它允许通过唯一键存储和查找几乎任何东西。 That means you can store the widgets with their title as a key and then later retrieve a widget with a certain title from that hash.
这意味着您可以将标题作为键存储在小部件中,然后从该散列中检索具有特定标题的小部件。
Here is how to define such a hash: 以下是如何定义这样的哈希:
// .h file
#include <QtCore/QHash>
#include <QtGui/QWidget>
class MyWidget : public QWidget
{
// ...
private:
QHash< QString, QWidget* > m_dynamicWidgetHash;
};
The Widgets (or any QWidget subclass) can then be stored in the hash like this, assuming the titles will always be unique : 然后,Widgets(或任何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 );
}
}
You can then later find your widgets knowing only the name like this: 然后,您可以稍后找到您的小部件,只知道这样的名称:
// .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
}
Also, it might be interested for you how to create object by class name using QMetaType
. 此外,它可能对您如何使用
QMetaType
按类名创建对象感兴趣。 There is QMetaType::construct
method. 有
QMetaType::construct
方法。 It requires that qRegisterMetaType
function is should be called before. 它要求之前应该调用
qRegisterMetaType
函数。 Detaild description is here . Detaild描述在这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.