The Property Browser Framework

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
Строка 20: Строка 20:
Кроме того, можно расширить фреймворк, написав собственные виджеты браузера, производные от класса <tt>QtAbstractPropertyBrowser</tt>.
Кроме того, можно расширить фреймворк, написав собственные виджеты браузера, производные от класса <tt>QtAbstractPropertyBrowser</tt>.
-
Custom editor widgets for propertiesare created by factories derived from the [[Qt:Документация_4.3.2/qabstracteditorfactory  | QAbstractEditorFactory]] class.
+
Настраиваемые виджеты редактора свойств, создаваемые фабриками, производными от класса [[Qt:Документация_4.3.2/qabstracteditorfactory  | QAbstractEditorFactory]].
-
Properties only need to be encapsulated in <tt>QtProperty</tt> instances beforethey can be used in browser widgets. These instances are created andmanaged by property managers derived from the <tt>QtAbstractPropertyManager</tt>class.
+
Свойства должны быть инкапсулированы только в экземплярах <tt>QtProperty</tt>, прежде чем они могут быть использованы в виджетах браузера. Эти экземпляры создаются и управляются менеджерами свойств, производными от класса <tt>QtAbstractPropertyManager</tt>.
<div id="populatingthepropertybrowser"></div>
<div id="populatingthepropertybrowser"></div>

Версия 18:19, 27 сентября 2020

Image:qt-logo_new.png Image:qq-title-article.png
Qt Quarterly | Выпуск 18 | Документация

by Jarek Kobus
Последний выпуск Qt Solutions включал решение Property Browser, конструкцию, предоставляющую набор графических редакторов для свойств Qt, похожих на те, что используются в Qt Designer.

Содержание

В этой статье мы подробно рассмотрим динамику классов Property Browser, представим два способа их использования в ваших приложениях, а также посмотрим, как фреймворк можно расширять с помощью типов и редакторов.

[source code]

The Big Picture

Фреймворк Property Browser включает в себя виджеты браузера, менеджеры свойств, фабрики свойств и сами свойства.

Виджеты браузера - это пользовательские интерфейсы, позволяющие пользователю редактировать заданный набор иерархически структурированных свойств: QtTreePropertyBrowser представляет свойства с использованием древовидных структур и QtGroupBoxPropertyBrowser отображает свойства в group box.

center

Кроме того, можно расширить фреймворк, написав собственные виджеты браузера, производные от класса QtAbstractPropertyBrowser.

Настраиваемые виджеты редактора свойств, создаваемые фабриками, производными от класса QAbstractEditorFactory.

Свойства должны быть инкапсулированы только в экземплярах QtProperty, прежде чем они могут быть использованы в виджетах браузера. Эти экземпляры создаются и управляются менеджерами свойств, производными от класса QtAbstractPropertyManager.

Populating the Property Browser

When using a property browser widget, managers must be created foreach of the required property types if we want the user to be able to editthe properties.

The framework provides managers for the most commontypes. For example, to create an integer property we first instantiatethe QtIntPropertyManager class, then we use its addProperty()function to create the property:

QtIntPropertyManager *intManager;
QtProperty *priority:
 
intManager = new QtIntPropertyManager;
priority = intManager->addProperty("Priority");
 
priority->setToolTip("Task Priority");
intManager->setRange(priority, 1, 5);
intManager->setValue(priority, 3);

The QtProperty class provides functions for setting a property's name,tooltip, status tip and "What's This?" text. To set and alter theproperty's value and range, each manager has its own type specificAPI. For example, here's how an enum property is set up and given adefault value:

QtEnumPropertyManager *enumManager;
QtProperty *reportType;
QStringList types;   
...
types << "Bug" << "Suggestion" << "To Do";
enumManager->setEnumNames(reportType, types);
enumManager->setValue(reportType, 1); // "Suggestion"

Properties can be categorized into groups using the QtGroupPropertyManagerclass. For example:

QtGroupPropertyManager *groupManager;
QtProperty *task1;
 
groupManager = new QtGroupPropertyManager;
task1 = groupManager->addProperty("Task 1");
 
task1->addSubProperty(priority);
task1->addSubProperty(reportType);

In addition, each property can have zero or more subproperties. These are justnormal properties that are added to a property using its addSubProperty()function.

The properties created by a group property manager don't have anyvalue, they are just provided as grouping elements in the propertyhierarchies and can be added to the browser in the same way as anyother property.

Once we have the properties, we associate each property manager with afactory for the preferred editor for that type. As with managers, the framework provides factoriesfor common widgets like QSpinBox and QComboBox.

QtSpinBoxFactory *spinBoxFactory;
QtEnumEditorFactory *enumFactory;
 
spinBoxFactory = new QtSpinBoxFactory;
enumFactory = new QtEnumEditorFactory;
 
QtTreePropertyBrowser *browser;
browser = new QtTreePropertyBrowser;
browser->setFactoryForManager(intManager, spinBoxFactory);
browser->setFactoryForManager(enumManager, enumFactory);

By relating a factory to a manager, we ensure that whenever a propertycreated by that manager appears in the browser, the specified factorywill be used to create an editor for it.

browser->addProperty(task1);
browser->show();

Finally, it only remains to add our properties to the browserand ensure that the browser widget is shown.

center

Note that to provide different editor widgets for the same propertytype, we only need to call setFactoryForManager() with another instanceof the type-specific factory.

Once the browser widget is populated, the user can interact with itand edit the properties. We can monitor the values of properties byconnecting to each property manager's signals, such asQtIntPropertyManager::valueChanged() andQtEnumPropertyManager::enumChanged().

The Variant Approach

In the previous section we populated the property browser usingspecialized classes for each property type. But the framework alsoprovides a convenient second approach that uses QVariant to holdall the properties' values and attributes.

In this approach, the developer only needs one property manager classand one editor factory class. These are selected from the followingthree classes:

  • QtVariantProperty inherits QtProperty but has anenriched API, allowing properties values and attributes to be directlyqueried and altered.
  • QtVariantPropertyManager can be used for all propertytypes, and its additional API can be used to query for supported variant typesand their attribute lists.
  • QtVariantEditorFactory is capable of creating variouseditor widgets for the types supported by QtVariantPropertyManager.

Using this approach, the code from the previous section to manage aninteger property now looks like this:

QtVariantPropertyManager *variantManager;
variantManager = new QtVariantPropertyManager;
 
QtVariantProperty *priority = variantManager->addProperty(QVariant::Int, "Priority");
priority->setAttribute("minimum", 1);
priority->setAttribute("maximum", 5);
priority->setValue(3);

Note the additional argument in the QtVariantManager::addProperty()function. It is the type of property we want to create. This can beany of values defined in the QVariant::Type enum plus additional uservalues obtained using the qMetaTypeId() function.

Subsequently, instead of calling setRange() onQtIntPropertyManager, we use the setAttribute() function ofQtVariantProperty class twice, passing minimum and maximum valuesfor the property. Finally, we call the setValue() function directlyon the QtVariantProperty instance.

The ID of an enum property is not built into QVariant, and must beobtained using the static QtVariantPropertyManager::enumTypeId()function.

QtVariantProperty *reportType = variantManager->addProperty(
    QtVariantPropertyManager::enumTypeId(), "Report Type");
QStringList types;
types << "Bug" << "Suggestion" << "To Do";
reportType->setAttribute("enumNames", types);
reportType->setValue(1); // "Suggestion"

Then we can call setAttribute() for the property,passing "enumNames" as the attribute name, to set the possible enumvalues that the property can have.

Group properties are created in the same way as enum properties, but withan ID retrieved using the QtVariantPropertyManager::groupTypeId()function.

In the end we create an instance of the QtVariantEditorFactory class,and use it with our variant manager in our chosen property browser:

 
QtTreePropertyBrowser *browser;
QtVariantEditorFactory *factory;
...
browser->setFactoryForManager(variantManager, factory);

Extending the Framework

So far we have used the existing properties, managers and factories providedby the Property Browser framework. But the framework also allows thedeveloper to create and support custom property types.

Let's say we want to extend our previous example, and support a customfile path property. The value of our custom property can be a QString, and the property can in addition possess afiltering attribute. We can also create a custom editor for our type,FileEdit, a simple composition of QLineEdit and QToolButton. We want to let the line edit show the current file path,and show a file browser dialog when the tool button is pressed (allowing theuser to choose a file from the files that match our filtering attribute).

The editor class provides getter and setter functions for its fields, aswell as a signal that can be emitted whenever the file path changes.

center

We have described two approaches for populating a browser widget:One uses type specific property managers and editor factories; the otheruses the framework's variant base classes. Both approaches support customtypes.

If we choose the type specific approach, we must provide a managerthat is able to produce properties of our custom type, and that canstore the state of the properties it creates; i.e., their values andattributes. Such a manager looks like this:

class FilePathManager : public QtAbstractPropertyManager
{
    ...
    QString value(const QtProperty *property) const;
    QString filter(const QtProperty *property) const;
public slots:
    void setValue(QtProperty *, const QString &amp;);
    void setFilter(QtProperty *, const QString &amp;);
signals:
    void valueChanged(QtProperty *, const QString &amp;);
    void filterChanged(QtProperty *, const QString &amp;);
protected:
    QString valueText(const QtProperty *property) const
        { return value(property); }
    void initializeProperty(QtProperty *property)
        { theValues[property] = Data(); }
    void uninitializeProperty(QtProperty *property)
        { theValues.remove(property); }
private:
    struct Data {
        QString value;
        QString filter;
    };
    QMap<const QtProperty *, Data> theValues;
};

Our custom FilePathManager is derived from theQtAbstractPropertyManager, enriching the interface with its attributes,and providing the required getter and setter functions for our custom property.The valueChanged() andfilterChanged() signals are used to communicate with custom editorfactories (shown later), and can also be generally used to monitor properties.We define a simple data structure to store the state ofthe value and filter for each file path property, and record each file pathproperty in a private map.

The FilePathManager must also reimplement several protectedfunctions provided by its base class that are needed by theframework: valueText() returns a string representation of the property'svalue, initializeProperty() initializes a new property, anduninitializeProperty() is used to clean up when a property is deleted.

We return empty data from getter functions if an unknown property issupplied; otherwise we return the data from the property map:

QString FilePathManager::value(const QtProperty *property)
        const
{
    if (!theValues.contains(property)) return "";
    return theValues[property].value;
}

In the setter functions, we ignore attempts to set the values of unknownproperties, and only commit new data to the property map. We emit thebase class's propertyChanged() signal to notify other components of anychanges. However, note that the setFilter() does not need to do thisbecause it does not change the property's value.

void FilePathManager::setValue(QtProperty *property, const QString &amp;val)
{
    if (!theValues.contains(property)) return;
    Data data = theValues[property];
    if (data.value == val) return;
    data.value = val;
    theValues[property] = data;
    emit propertyChanged(property);
    emit valueChanged(property, data.value);
}

Before we can add instances of our custom property to the browserwidget, we must also provide a factory which is able to produceFileEdit editors for our property manager:

class FileEditFactory
    : public QtAbstractEditorFactory<FilePathManager>
{
    ...
private slots:
    void slotPropertyChanged(QtProperty *property,
                             const QString &amp;value);
    void slotFilterChanged(QtProperty *property,
                           const QString &amp;filter);
    void slotSetValue(const QString &amp;value);
    void slotEditorDestroyed(QObject *object);
private:
    QMap<QtProperty *, QList<FileEdit *> > createdEditors;
    QMap<FileEdit *, QtProperty *> editorToProperty;
};

The FileEditFactory is derived from the QtAbstractEditorFactorytemplate class, using our FilePathManager class as the templateargument. This means that our factory is only able to create editorsfor our custom manager while allowing it to access the manager's enrichedinterface.

As with the manager, the custom factory must reimplement some protectedfunctions. For example, the connectPropertyManager() function iscalled when the factory is set up for use with a FilePathManager,and connects the manager's valueChanged() and filterChanged()signals to the corresponding slotPropertyChanged() andslotFilterChanged() slots. These connections keep the state of theeditors up to date. Similarly, disconnectPropertyManager() is used toremove these connections.

The createEditor() function creates and initializes a FileEditwidget, adds the editor to the internal maps:

FileEdit *editor = new FileEdit(parent);
editor->setFilePath(manager->value(property));
editor->setFilter(manager->filter(property));
createdEditors[property].append(editor);
editorToProperty[editor] = property;
 
connect(editor, SIGNAL(filePathChanged(const QString &amp;)),
        this, SLOT(slotSetValue(const QString &amp;)));
connect(editor, SIGNAL(destroyed(QObject *)),
        this, SLOT(slotEditorDestroyed(QObject *)));
return editor;

Before returning the new editor widget, we connect its filePathChanged()signal to the factory's slotSetValue() slot. We also connect itsdestroyed() signal to the factory's slotEditorDestroyed() slot toensure that we are notified if it is destroyed.

Internally, the task of each factory is to synchronize the state of theeditors with the state of the properties. Whenever an editor changesits value we need to tell the framework about it, and vice versa.In our editor factory's editorToProperty map, we relate every editorcreated by the factory to the property it was created to edit.

The opposite relation is kept in the createdEditors map, whereproperties are related to editors. Since it is possible that two or moreproperty browsers are displaying the same instance of a property, we mayneed to create many editors for the same property instance, so we keep alist of editors for each property.

Combined with the private slots, these data structures allow us toinform the framework that an editor value has been changed, and let usupdate all relevant editors whenever the framework changes any of theproperties.

When the factory is destroyed, the state of the properties is no longersynchronized, and the data shown by the editors is no longer valid. For thatreason, all the editors created by the factory are deleted in the factory'sdestructor. Therefore, when an editor is destroyed, we must ensure that itis removed from the internal maps.

The process of adding a custom property is equivalent to adding any otherproperty:

FilePathManager *filePathManager;
FileEditFactory *fileEditFactory 
QtProperty *example;
 
filePathManager = new FilePathManager;
example = filePathManager->addProperty("Example");
 
filePathManager->setValue(example, "main.cpp");
filePathManager->setFilter(example, 
                           "Source files (*.cpp *.c)");
 
fileEditFactory = new FileEditFactory;
browser->setFactoryForManager(filePathManager, fileEditFactory);
task1->addSubProperty(example);

Extending with Variants

The variant-based approach can also be used for custom types. Using thisapproach, we derive our manager from QtVariantPropertyManager and ourfactory from QtVariantPropertyFactory.

In the previous example, the FilePathManager class handled the datainternally for our custom property type. In this case, we define theproperty type as a path value with an associated filter attribute. Both thepath and the filter are stored as strings, and we define a new property typefor the file path as a whole:

class FilePathPropertyType
{
};
Q_DECLARE_METATYPE(FilePathPropertyType)

The custom manager must reimplement several inherited functions andprovide a static function to return the new property type:

int VariantManager::filePathTypeId()
{
    return qMetaTypeId<FilePathPropertyType>();
}

This function returns a unique identifier for our file path property typethat can be passed to QtVariantPropertyManager::addProperty() tocreate new file path properties.

Unlike the FilePathManager class, all the functions inherited fromthe base class already have an implementation; all we have to do is tointercept the process whenever our custom property type occurs. Forexample, when reimplementing the isPropertyTypeSupported()function we should return true for our custom type, and callthe base class implementation for all other types:

bool VariantManager::isPropertyTypeSupported(
     int propertyType) const
{
    if (propertyType == filePathTypeId())
        return true;
    return QtVariantPropertyManager::
        isPropertyTypeSupported(propertyType);
}

The VariantFactory class, like every other editor factory, doesnot have to provide any new members. Basically, the implementationis very similar to FileEditFactory in the previous section. The onlydifference in the connectPropertyManager() function is that we mustconnect the manager's attributeChanged() signal to a generalslotPropertyAttributeChanged() slot instead of connecting a specificsignal for the filter to a specific slot to handle changes.

We also need to check that the property can handle our custom type in thecreateEditor() function:

if (manager->propertyType(property) == VariantManager::filePathTypeId()) {
  ...
  connect(editor, SIGNAL(filePathChanged(const QString&amp;)),
          this, SLOT(slotSetValue(const QString &amp;)));
  connect(editor, SIGNAL(destroyed(QObject *)),
          this, SLOT(slotEditorDestroyed(QObject *)));
  return editor;
}
...

We also monitor the editor via its destroyed() and customfilePathChanged() signals.

Using custom variant managers and factories is no different thanusing those delivered by the framework:

QtVariantPropertyManager *variantManager;
variantManager = new VariantManager;
QtVariantEditorFactory *variantFactory;
variantFactory = new VariantFactory;
 
QtVariantProperty *example;
example = variantManager->addProperty(
          VariantManager::filePathTypeId(), "Example");
example->setValue("main.cpp");
example->setAttribute("filter", "Source files (*.cpp *.c)");
 
QtVariantProperty *task1;
task1 = variantManager->addProperty(
    QtVariantPropertyManager::groupTypeId(), "Task 1");
task1->addSubProperty(example);

All that's left to do is to set up the browser to use the propertymanager and factory in the same way as before.

Summary

The Property Browser Solution provides a framework for creating propertyeditors that can be used and extended with either a type-specificor a variant-based API.

The type-specific approach provides a specialized API for each property thatmakes compile-time checking possible. In this approach, the managers andfactories can easily be subclassed and used in other projects. In addition,the developer can customize the property browser with new editorfactories without subclassing.

The variant-based approach provides immediate convenience for the developer,allowing simple, extensible code to be written. However, it can be difficultto integrate into a more complex code base, and QtVariantEditorFactorymust be subclassed to change the default editors.

The first release of the Property Browser framework contained a comprehensive set of examples and documentation. A new version, incorporatingseveral new improvements is expected in the next Qt Solutions release.


Copyright © 2006 Trolltech Trademarks