나는 QHash
이 귀하의 필요에 맞는 완벽한 도구라고 생각합니다. 고유 한 키를 통해 거의 모든 것을 저장하고 조회 할 수 있습니다. 즉, 제목과 함께 위젯을 키로 저장 한 다음 나중에 해당 해시에서 특정 제목이있는 위젯을 검색 할 수 있습니다.
는 위젯 (또는는 QWidget 서브 클래스는) 다음과 같은 해시에 저장 될 수
// .h file
#include <QtCore/QHash>
#include <QtGui/QWidget>
class MyWidget : public QWidget
{
// ...
private:
QHash< QString, QWidget* > m_dynamicWidgetHash;
};
, 제목을 가정 항상 독특한 될 것입니다 : 여기
는 해시를 정의하는 방법입니다
// .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
}
+1 Qhash ... 어떻게하면 알 수 있습니까? – UmNyobe
Qt는 문서의 어딘가에 숨겨진 많은 멋진 것들을 가지고 있습니다 ;-) 당신이 처음이라면 [Container Classes] (http://qt-project.org/doc/qt-4.8/containers.html)를 읽는 것이 좋습니다. –
@Tim Meyer 훌륭합니다! 고맙습니다! –