Редактирование: Designing Delegates

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

Перейти к: навигация, поиск
Внимание: Вы не представились системе. Ваш IP-адрес будет записан в историю изменений этой страницы.
Правка может быть отменена. Пожалуйста, просмотрите сравнение версий, чтобы убедиться, что это именно те изменения, которые вас интересуют, и нажмите «Записать страницу», чтобы изменения вступили в силу.
Текущая версия Ваш текст
Строка 13: Строка 13:
===<div id="anexpandingtree"></div>An Expanding Tree===
===<div id="anexpandingtree"></div>An Expanding Tree===
-
Итак, наша цель - создание элемента заголовка, по которому можно щелкнуть. Когда по нему щелкаем, он раскроется, для того чтобы показать набор подэлементов. Когда по ним щелкаем, эти элементы могут выводить информацию или выполнять действие. Наконец, группируя эти элементы в логической последовательности, мы будем учитывать пустые пространства (whitespace) (или пробелы) в дереве.
+
So, our goal is to create a header item that can be clicked. When clicked, it will expand to show a number of sub-items. These items can display information or perform an action when clicked. Finally, to group these items in a logical way, we will allow for whitespace (or blank) items in the tree.
[[Image:qq24-delegates-expanded-tree.png|center]]
[[Image:qq24-delegates-expanded-tree.png|center]]
-
Мы используем два класса: делегат (delegate) для обеспечения визуализации и помощник (helper) для обеспечения функциональности. До этого, нам необходимо создать [[Qt:Документация_4.3.2/QTreeView | QTreeView]] и подготовить для него модель. Здесь исходный код показывает как заполняется группа элементов.
+
We use two classes: a delegate for the visuals and a helper for the functionality. Prior to that, we need to create a [[Qt:Документация_4.3.2/QTreeView | QTreeView]] and provide it with a model. The source code here shows how a group of items is populated.
<source lang="cpp-qt">
<source lang="cpp-qt">
     void TreeDialog::populateTree()
     void TreeDialog::populateTree()
Строка 44: Строка 44:
</source>  
</source>  
-
Вся модель основывается на [[Qt:Документация_4.3.2/qstandarditemmodel | QStandardItemModel]]. Она позволяет нам заполнить модель и установить различные роли данных для каждого элемента. Поскольку группа показана на верхнем уровне, родитель первого элемента в моделе - <tt>invisibleRootItem</tt>. Остальные элементы в дереве являются его детьми.
+
The whole model is based on [[Qt:Документация_4.3.2/qstandarditemmodel | QStandardItemModel]]. It allows us to populate the model and set a different data role for each item. As the group is shown at the top level, the parent of the first item is the <tt>invisibleRootItem</tt> of the model. The other tree items are children of the first item.
-
Каждому элементу в конструкторе [[Qt:Документация_4.3.2/qstandarditem | QStandardItem]]() назначается <tt>DisplayItem</tt>. Затем устанавливаются <tt>DecorationRole</tt> и <tt>BackgroundColorRole</tt>, и далее следуют пользовательские <tt>TypeRole</tt> и <tt>SignalValueRole</tt>. Позднее две роли придут из нашего класса помощника, <tt>ExpHelper</tt>.
+
Each item is given a <tt>DisplayItem</tt> through the [[Qt:Документация_4.3.2/qstandarditem | QStandardItem]]() constructor. Then the <tt>DecorationRole</tt> and a <tt>BackgroundColorRole</tt> are set, followed by the custom <tt>TypeRole</tt> and <tt>SignalValueRole</tt>. The latter two roles come from our helper class, <tt>ExpHelper</tt>.
-
=== Класс Помощник ===
+
 
-
<tt>TypeRole</tt> может принимать значение либо <tt>Spacer</tt>, либо <tt>Item</tt>. Каждое из них будет обрабатываться нашим делегатом. <tt>SignalValueRole</tt> позволяет нам установить значение, формируемое сигналом, когда по элементу щелкают. Как показано далее, и роли, и типы определены как перечисления (enumerations) в <tt>ExpHelper</tt>.
+
===<div id="thehelperclass"></div>The Helper Class===
 +
The <tt>TypeRole</tt> can either be a <tt>Spacer</tt> or an <tt>Item</tt>, both of which will be handled by our delegate. The <tt>SignalValueRole</tt> allows us to set the value that is provided with a signal when an item is clicked. Both the roles and the types are defined as enumerations in <tt>ExpHelper</tt> as shown below.
<source lang="cpp-qt">
<source lang="cpp-qt">
     class ExpHelper : public QObject
     class ExpHelper : public QObject
Строка 64: Строка 65:
      
      
     private slots:
     private slots:
-
       void itemClicked(const QModelIndex &index);
+
       void itemClicked(const QModelIndex &amp;index);
      
      
     private:
     private:
Строка 71: Строка 72:
</source>  
</source>  
-
Класс помощник предназначен для того, чтобы сделать поведение данного [[Qt:Документация_4.3.2/qtreeview | QTreeView]] подобным раскрывающемуся дереву. Конструктор принимает [[Qt:Документация_4.3.2/qtreeview | QTreeView]] как родителя. Мы определяем перечисления для типов и ролей, подобно сигналу <tt>itemClicked(int)</tt>. Аргумент integer, передавемый данному сигналу, является значением принятым <tt>SignalValueRole</tt> во время создания элемента.
+
The role of the helper class is to make a given [[Qt:Документация_4.3.2/qtreeview | QTreeView]] behave like an expanding tree. The constructor accepts a [[Qt:Документация_4.3.2/qtreeview | QTreeView]] as its parent; we define enumerations for the types and the roles, as well as the <tt>itemClicked(int)</tt> signal. The integer passed as an argument to this signal is the value given as the <tt>SignalValueRole</tt> when creating the item.
-
Завершающая private часть класса включает слот, соответствующий сигналу <tt>itemClicked(int)</tt> и указатель на представление (view), которому помощник принадлежит. Для того, чтобы увидеть как они вписываются в картину, рассмотрим конструктор:
+
 
 +
The end of the class is part of the private implementation: a slot corresponding to the <tt>itemClicked(int)</tt> signal and a pointer to the view which the helper belongs to. To see how these fit into the picture, have a look at the constructor implementation:
<source lang="cpp-qt">
<source lang="cpp-qt">
     ExpHelper::ExpHelper(QTreeView *parent)
     ExpHelper::ExpHelper(QTreeView *parent)
Строка 142: Строка 144:
Stepping back, we can see that the helper not only provides the functionality but also the appearance, in the form of a delegate.
Stepping back, we can see that the helper not only provides the functionality but also the appearance, in the form of a delegate.
 +
===<div id="theappearanceofadelegate"></div>The Appearance of a Delegate===
===<div id="theappearanceofadelegate"></div>The Appearance of a Delegate===
Строка 315: Строка 318:
I'm sure that you can find numerous other tricks for both the delegate and the helper. For example, items that expand with a timer, expandable sub-items, and so on. Feel free to download the source code for this article and play around with the examples.
I'm sure that you can find numerous other tricks for both the delegate and the helper. For example, items that expand with a timer, expandable sub-items, and so on. Feel free to download the source code for this article and play around with the examples.
-
=== Ссылки ===
+
[http://www.forum.crossplatform.ru/index.php?showtopic=701 Обсудить...]
-
* [http://www.crossplatform.ru/uploads/articles/sources/qq24-delegates.zip Пример кода]
+
-
* [http://www.forum.crossplatform.ru/index.php?showtopic=701 Обсудить...]
+
[[Категория:Qt_Издания]]
[[Категория:Qt_Издания]]

Пожалуйста, обратите внимание, что все ваши добавления могут быть отредактированы или удалены другими участниками. Если вы не хотите, чтобы кто-либо изменял ваши тексты, не помещайте их сюда.
Вы также подтверждаете, что являетесь автором вносимых дополнений, или скопировали их из источника, допускающего свободное распространение и изменение своего содержимого (см. Wiki.crossplatform.ru:Авторское право). НЕ РАЗМЕЩАЙТЕ БЕЗ РАЗРЕШЕНИЯ ОХРАНЯЕМЫЕ АВТОРСКИМ ПРАВОМ МАТЕРИАЛЫ!


Шаблоны, использованные на текущей версии страницы: