Пример Custom Widget Plugin
Файлы:
Пример Custom Widget показывает, как создать подключаемый модуль пользовательского виджета для Qt Designer'а.
В этом примере, используется пользовательский виджет на основе примера Analog Clock , и не предоставляет пользовательских сигналов и слотов. ПодготовкаЧтобы предоставить пользовательский виджет, который может быть использован с Qt Designer'ом, мы должны обеспечить самодостаточную реализацию и предоставить интерфейс подключения. В этом примере, мы, для удобства, повторно используем пример Analog Clock. Так как подключаемый модуль пользовательского виджета зависит от компонентов применяемых с Qt Designer'ом, то файл проекта, который мы используем, должен содержать информацию о библиотечных компонентах Qt Designer'а: TEMPLATE = lib CONFIG += designer plugin debug_and_release Значение переменной TEMPLATE указвает qmake создать пользовательский виджет как библиотеку. Позднее, мы позаботимся о том, чтобы виджет был распознан как подключаемый модуль Qt, используя макрос Q_EXPORT_PLUGIN2(), чтобы экспортировать информацию связанную с виджетом. Переменная CONFIG содержит два значения - designer и plugin:
Когда Qt сконфигурирована в обоих режимах debug и release, Qt Designer будет собран в release режиме. В этом случае, необходимо гарантировать, что подключаемый модуль также был собран в режиме release. Для этого случая мы добавили значение debug_and_release в переменную CONFIG. В противном случае, если подключаемый модуль собран в режиме, который несовместим с Qt Designer, он не будет загружен и установлен. Заголовочные и исходные файлы для виджета объявляются обычным способом, и мы предоставляем реализацию интерфейса подключаемого модуля так, что Qt Designer может использовать пользовательский виджет: HEADERS = analogclock.h \
customwidgetplugin.h
SOURCES = analogclock.cpp \
customwidgetplugin.cpp
Также важно гарантировать, что подключаемый модуль устанавливается в то самое место, где его будет искать Qt Designer. Мы делаем это, определяя целевой путь для проекта и добавляя его в список элементов для установки: target.path = $$[QT_INSTALL_PLUGINS]/designer INSTALLS += target Пользовательский виджет будет создан как библиотека и будет установлен рядом с другими подключаемыми модулями Qt Designer'а, когда проект будет установлен (используйте make install или другую эквивалентную процедуру). Позднее, мы позаботимся, чтобы он распознавался как подключаемый модуль Qt Designer'а, используя макрос Q_EXPORT_PLUGIN2(), чтобы экспортировать информацию связанную с виджетом. Заметьте, что если вы хотите, чтобы подключаемый модуль отображался в интеграторе Visual Studio, подключаемый модуль должен быть собран в режиме release и его библиотеки должны быть скопированы в каталог подключаемых модулей, где установлен интегратор (например, см. C:/program files/trolltech as/visual studio integration/plugins). Для получения дополнительной информации о подключаемых модулях, смотрите документацию Как создавать плагины Qt. Объявление и реализация класса AnalogClockКласс AnalogClock объявлен и реализован в точности так же, как описано в примере Analog Clock. Так как класс самодостаточен и не требует внешней конфигурации, он может быть использован без изменений как пользовательский виджет в Qt Designer'е. Объявление класса AnalogClockPluginКласс AnalogClock взаимодействует с Qt Designer'ом через класс AnalogClockPlugin. Этот класс унаследован от двух классов, QObject и QDesignerCustomWidgetInterface и реализует интерфейс, определенный в QDesignerCustomWidgetInterface: class AnalogClockPlugin : public QObject, public QDesignerCustomWidgetInterface
{
Q_OBJECT
Q_INTERFACES(QDesignerCustomWidgetInterface)
public:
AnalogClockPlugin(QObject *parent = 0);
bool isContainer() const;
bool isInitialized() const;
QIcon icon() const;
QString domXml() const;
QString group() const;
QString includeFile() const;
QString name() const;
QString toolTip() const;
QString whatsThis() const;
QWidget *createWidget(QWidget *parent);
void initialize(QDesignerFormEditorInterface *core);
private:
bool initialized;
};
Функции предоставляют информацию о виджете, который может быть использован в списке виджетов (widget box) Qt Designer'а. Частная переменная-член initialized используется, чтобы записать, инициализирован ли Qt Designer'ом подключаемый модуль или нет . Заметьте, что only part of the class definition that is specific to this particular custom widget is the class name. Реализация AnalogClockPluginКонструктор класса просто вызывает конструктор базового класса QObject и устанавливает переменную initialized в значение false. AnalogClockPlugin::AnalogClockPlugin(QObject *parent)
: QObject(parent)
{
initialized = false;
}
Qt Designer will initialize the plugin when it is required by calling the initialize() function: void AnalogClockPlugin::initialize(QDesignerFormEditorInterface * /* core */)
{
if (initialized)
return;
initialized = true;
}
In this example, the initialized private variable is tested, and only set to true if the plugin is not already initialized. Although, this plugin does not require any special code to be executed when it is initialized, we could include such code after the test for initialization. The isInitialized() function lets Qt Designer know whether the plugin is ready for use: bool AnalogClockPlugin::isInitialized() const
{
return initialized;
}
Instances of the custom widget are supplied by the createWidget() function. The implementation for the analog clock is straightforward: QWidget *AnalogClockPlugin::createWidget(QWidget *parent)
{
return new AnalogClock(parent);
}
In this case, the custom widget only requires a parent to be specified. If other arguments need to be supplied to the widget, they can be introduced here. The following functions provide information for Qt Designer to use to represent the widget in the widget box. The name() function returns the name of class that provides the custom widget: QString AnalogClockPlugin::name() const
{
return "AnalogClock";
}
The group() function is used to describe the type of widget that the custom widget belongs to: QString AnalogClockPlugin::group() const
{
return "Display Widgets [Examples]";
}
The widget plugin will be placed in a section identified by its group name in Qt Designer's widget box. The icon used to represent the widget in the widget box is returned by the icon() function: QIcon AnalogClockPlugin::icon() const
{
return QIcon();
}
In this case, we return a null icon to indicate that we have no icon that can be used to represent the widget. A tool tip and "What's This?" help can be supplied for the custom widget's entry in the widget box. The toolTip() function should return a short message describing the widget: QString AnalogClockPlugin::toolTip() const
{
return "";
}
The whatsThis() function can return a longer description: QString AnalogClockPlugin::whatsThis() const
{
return "";
}
The isContainer() function tells Qt Designer whether the widget is supposed to be used as a container for other widgets. If not, Qt Designer will not allow the user to place widgets inside it. bool AnalogClockPlugin::isContainer() const
{
return false;
}
Most widgets in Qt can contain child widgets, but it only makes sense to use dedicated container widgets for this purpose in Qt Designer. By returning false, we indicate that the custom widget cannot hold other widgets; if we returned true, Qt Designer would allow other widgets to be placed inside the analog clock and a layout to be defined. The domXml() function provides a way to include default settings for the widget in the standard XML format used by Qt Designer. In this case, we only specify the widget's geometry: QString AnalogClockPlugin::domXml() const
{
return "<widget class=\"AnalogClock\" name=\"analogClock\">\n"
" <property name=\"geometry\">\n"
" <rect>\n"
" <x>0</x>\n"
" <y>0</y>\n"
" <width>100</width>\n"
" <height>100</height>\n"
" </rect>\n"
" </property>\n"
" <property name=\"toolTip\" >\n"
" <string>The current time</string>\n"
" </property>\n"
" <property name=\"whatsThis\" >\n"
" <string>The analog clock widget displays "
"the current time.</string>\n"
" </property>\n"
"</widget>\n";
}
If the widget provides a reasonable size hint, it is not necessary to define it here. In addition, returning an empty string instead of a <widget> element will tell Qt Designer not to install the widget in the widget box. To make the analog clock widget usable by applications, we implement the includeFile() function to return the name of the header file containing the custom widget class definition: QString AnalogClockPlugin::includeFile() const
{
return "analogclock.h";
}
В заключение, мы используем макрос Q_EXPORT_PLUGIN2(), чтобы экспортировать класс AnalogClockPlugin для использования с Qt Designer'ом: Q_EXPORT_PLUGIN2(customwidgetplugin, AnalogClockPlugin) Этот макрос гарантирует, что Qt Designer может получить доступ к пользовательскому виджету и конструировать его. Без этого макроса не существует способа, чтобы использовать виджет в Qt Designer'е.
|
|
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |