С Новым годом! Форум программистов, компьютерный форум, киберфорум
QML
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.55/11: Рейтинг темы: голосов - 11, средняя оценка - 4.55
0 / 0 / 0
Регистрация: 17.03.2016
Сообщений: 28

"Error creating delegate" при прокрутке списков QML

22.11.2016, 17:25. Показов 2303. Ответов 4

Студворк — интернет-сервис помощи студентам
Здравствуйте. Есть 2 списка: GridView и ListView.
Если добавить в них добавить больше 10 элементов и резко листнуть список, то некоторые элементы не успевают загрузиться (вместо них пустота) и в консоль QtCreator'a сыпятся такие сообщения:
Code
1
<Unknown File>: QML VisualDataModel: Error creating delegate
Код ListView вместе с делегатом:
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
ListView{
        id: servoListView
        objectName: "servoListView"
        //anchors.fill: parent
        anchors.topMargin: 16        
        spacing: 16
        width: parent.width
        footerPositioning: ListView.InlineFooter
        ScrollIndicator.vertical: ScrollIndicator{}
 
        add: Transition{
            NumberAnimation { property: "opacity"; from: 0; to: 1.0; duration: 200 }
        }
        addDisplaced: Transition {
            NumberAnimation { properties: "x,y"; duration: 200 }
        }
        
        footer: Component{
            Rectangle{
                width: parent.width
                height: servoFab.height + (servoFab.anchors.margins * 2)
                color: "transparent"
            }
        }        
 
        header: Component{
            Rectangle{
                width: parent.width
                height: pageNameText.height + 16
                color: "transparent"
                Label{
                    id: pageNameText
                    text: "Управление сервоприводами"
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.top: parent.top
                }
            }
        }
 
        delegate: Item {
            id: newServo
            height: servoControllerLayout.height + listDivider.height + servoControllerLayout.anchors.topMargin
            width: parent.width
 
            property string commandToSend: command
 
            GridLayout{
                id: servoControllerLayout
                columns: 2
                rows: 3
                rowSpacing: 8
                anchors.left: parent.left
                anchors.right: parent.right
 
                Label{
                    id: servoName
                    anchors.left: parent.left
                    anchors.leftMargin: 16
                    Layout.column: 0
                    Layout.row:0
                    Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
                    Layout.fillWidth: true
                    text: name
                }
                Slider{
                    id: positionSlider
                    anchors.left: parent.left
                    anchors.leftMargin: 16
                    Layout.column: 0
                    Layout.row: 1
                    Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
                    from: min
                    to: max
                    value: val
                    snapMode: Slider.SnapAlways
                    stepSize: 1.000000000000000
                    Layout.fillWidth: true
 
                    onValueChanged: {
                        //send()
                    }
                }
                Label{
                    id: servoValLabel
                    anchors.left: parent.left
                    anchors.leftMargin: 16
                    Layout.column: 0
                    Layout.row: 2
                    Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
                    text: positionSlider.value.toFixed(0) + "/" + positionSlider.to
                }
                Button{
                    id: servoSettingsButton
                    flat: true
                    Layout.column: 1
                    Layout.row:0
                    Layout.rowSpan: 2
                    Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
                    Layout.maximumWidth: parent.width / 7
                    contentItem: Image {
                        fillMode: Image.Pad
                        horizontalAlignment: Image.AlignHCenter
                        verticalAlignment: Image.AlignVCenter
                        source: "qrc:/images/+material/settings.svg"
                        sourceSize.width: 32
                        sourceSize.height: 32
                        opacity: 0.54
                    }
                    onClicked: {
                        mainStack.servoToEdit = index
                        mainStack.push("qrc:/ServoSettingsPage.qml")
                    }
                }
            }
            Rectangle{
                width: 6
                height: newServo.height + 16
                x: 0
                anchors.bottom: listDivider.bottom
                color: scolor
            }
 
            Rectangle{
                id: listDivider
                width: servoControlPage.width
                height: 1
                anchors.top: servoControllerLayout.bottom
                anchors.topMargin: 8
                color: "#000000"
                opacity: 0.12
            }
        }
        model: servoListModel
    }
Используемая модель с данными роли не играет. Ошибка появляется как со стандартными ListModel, так и собственными (унаследованными от QAbstractItemModel).
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
22.11.2016, 17:25
Ответы с готовыми решениями:

error C3374 can't take address of 'function' unless creating delegate instance
Здравствуйте! При попытке создания многопоточного приложения столкнулась с такой ошибкой: Error 1 error C3374: can't take address of...

can't take adress of function unless creating delegate instance
Здравствуйте, есть проблема - использую ф-ию &quot;pr&quot; как ф-ию потока но выдает ошибку &quot;can't take adress of &amp;poker::Form1::tr unless...

Error creating bean with name 'mvcValidator' и Error creating bean with name 'requestMappingHandlerAdapter'
Собираю проект. Есть класс AppConfig @Configuration @EnableWebMvc @ComponentScan(&quot;ru.liberty.ms.*&quot;) public class AppConfig...

4
 Аватар для Wyn
1073 / 654 / 230
Регистрация: 14.01.2016
Сообщений: 2,031
Записей в блоге: 9
23.11.2016, 13:27
JavaScript
1
2
delegate: Item {
     width: parent.width
Насколько помню такое не работает. Там parent другой. Нужно указывать явно - servoListView.width.
JavaScript
1
2
3
Label{
     id: servoName
     anchors.left: parent.left
Какой ещё parent.left, если данный элемент заносится в Grid Cell? Для подобных целей используется только Layout.alignment.

А в целом смотрите на QML профайлер, где у вас самые ресурсоёмкие операции и оптимизируйте их.
1
0 / 0 / 0
Регистрация: 17.03.2016
Сообщений: 28
23.11.2016, 18:44  [ТС]
Wyn, почистил код, убрал все anchor'ы из GridLayout. Удалось значительно снизить кол-во появляющихся ошибок, да и делегаты перестали пропадать из списка.

Новый код:
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
ListView{
        id: servoListView
        objectName: "servoListView"
        width: parent.width
        anchors{fill: parent; leftMargin: 16; topMargin: 16;}
        spacing: 16
        footerPositioning: ListView.InlineFooter
        ScrollIndicator.vertical: ScrollIndicator{}
 
        add: Transition{
            NumberAnimation { property: "opacity"; from: 0; to: 1.0; duration: 200 }
        }
        addDisplaced: Transition {
            NumberAnimation { properties: "x,y"; duration: 200 }
        }
        
        footer: Component{
            Rectangle{
                width: parent.width
                height: servoFab.height + (servoFab.anchors.margins * 2)
                color: "transparent"
            }
        }        
 
        header: Component{
            Rectangle{
                width: parent.width
                height: pageNameText.height + 16
                color: "transparent"
                Label{
                    id: pageNameText
                    text: "Управление сервоприводами"
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.top: parent.top
                }
            }
        }
 
        delegate: Item {
            id: newServo
            height: servoControllerLayout.height + listDivider.height + servoControllerLayout.anchors.topMargin
            width: servoListView.width
 
            property string commandToSend: command
 
            GridLayout{
                id: servoControllerLayout
                columns: 2
                rows: 3
                rowSpacing: 8
                width: newServo.width
 
                Label{
                    id: servoName
                    Layout.column: 0
                    Layout.row:0
                    Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
                    Layout.fillWidth: true
                    text: name
                }
                Slider{
                    id: positionSlider
                    Layout.column: 0
                    Layout.row: 1
                    Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
                    from: min
                    to: max
                    value: val
                    snapMode: Slider.SnapAlways
                    stepSize: 1.000000000000000
                    Layout.fillWidth: true
 
                    onValueChanged: {
                        //send()
                    }
                }
                Label{
                    id: servoValLabel
                    Layout.column: 0
                    Layout.row: 2
                    Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
                    text: positionSlider.value.toFixed(0) + "/" + positionSlider.to
                }
                Button{
                    id: servoSettingsButton
                    flat: true
                    Layout.column: 1
                    Layout.row:0
                    Layout.rowSpan: 2
                    Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
                    Layout.maximumWidth: parent.width / 7
                    contentItem: Image {
                        asynchronous: true
                        fillMode: Image.Pad
                        horizontalAlignment: Image.AlignHCenter
                        verticalAlignment: Image.AlignVCenter
                        source: "qrc:/images/+material/settings.svg"
                        sourceSize.width: 32
                        sourceSize.height: 32
                        opacity: 0.54
                    }
                    onClicked: {
                        mainStack.servoToEdit = index
                        mainStack.push("qrc:/ServoSettingsPage.qml")
                    }
                }
            }
            Rectangle{
                x: 0
                width: 6
                height: newServo.height + 16
                anchors.bottom: listDivider.bottom
                color: scolor
            }
 
            Rectangle{
                id: listDivider
                width: servoControlPage.width
                height: 1
                anchors{top: servoControllerLayout.bottom; topMargin: 8}
                color: "#000000"
                opacity: 0.12
            }
        }
        model: servoListModel
    }
Стал копать дальше, попробовал убрать загрузку svg картинки из делегата servoSettingsButton и ошибки перестали появляться вообще.
Дальше попробовал заменить векторные иконки на png, но ошибок стало еще больше.
Еще попробовал к картинкам добавить настройку asynchronous: true, но это тоже не особо помогло.

Как еще можно оптимизировать загрузку svg картинок, с учетом того, что они все одинаковые и должны быть в каждом делегате?
0
 Аватар для Wyn
1073 / 654 / 230
Регистрация: 14.01.2016
Сообщений: 2,031
Записей в блоге: 9
25.11.2016, 10:47
Цитата Сообщение от Mixxxxa Посмотреть сообщение
Как еще можно оптимизировать загрузку svg картинок, с учетом того, что они все одинаковые и должны быть в каждом делегате?
Поиграйся с настройками картинок. Что-то по теме помню, что там не всё так просто с sourceSize.width и sourceSize.height, что там иногда лучше такие оптимизации не проводить, используя вместо них соответствующий fillMode. Попробуй поотключать asynchronous. И т.д. и т.п.
1
0 / 0 / 0
Регистрация: 17.03.2016
Сообщений: 28
26.11.2016, 17:28  [ТС]
Wyn, покрутил я эти списки с пол дня и пришел к тому, что указал кэш списка с запасом на 10 элементов (примерно 1 экран) и кнопку с картинкой убрал в загрузчик. Теперь ни на компьютере, ни на телефоне проблем не наблюдается.

Может кому будет нужно, полный код ListView:
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
ListView{
        id: servoListView
        objectName: "servoListView"
        width: parent.width
        anchors{fill: parent; leftMargin: 16; topMargin: 16;}
        spacing: 16
        footerPositioning: ListView.InlineFooter
        cacheBuffer: 100 * 10 //Кэш примерно на 10 элементов (высота делегата * кол-во)
        ScrollIndicator.vertical: ScrollIndicator{}
 
        add: Transition{
            NumberAnimation { property: "opacity"; from: 0; to: 1.0; duration: 200 }
        }
        addDisplaced: Transition {
            NumberAnimation { properties: "x,y"; duration: 200 }
        }
 
        footer: Component{
            Rectangle{
                width: parent.width
                height: servoFab.height + (servoFab.anchors.margins * 2)
                color: "transparent"
            }
        }        
 
        header: Component{
            Rectangle{
                width: parent.width
                height: pageNameText.height + 16
                color: "transparent"
                Label{
                    id: pageNameText
                    text: "Управление сервоприводами"
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.top: parent.top
                }
            }
        }
 
        delegate: Item {
            id: newServo
            height: servoControllerLayout.height + listDivider.height + servoControllerLayout.anchors.topMargin
            width: servoListView.width
 
            property string commandToSend: command
            Component.onCompleted: console.log(name)
 
            GridLayout{
                id: servoControllerLayout
                columns: 2
                rows: 3
                rowSpacing: 8
                width: newServo.width
 
                Label{
                    id: servoName
                    Layout.column: 0
                    Layout.row:0
                    Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
                    Layout.fillWidth: true
                    text: name
                }
                Slider{
                    id: positionSlider
                    Layout.column: 0
                    Layout.row: 1
                    Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
                    from: min
                    to: max
                    value: val
                    snapMode: Slider.SnapAlways
                    stepSize: 1.000000000000000
                    Layout.fillWidth: true
 
                    onValueChanged: {
                        //send()
                    }
                }
                Label{
                    id: servoValLabel
                    Layout.column: 0
                    Layout.row: 2
                    Layout.alignment: Qt.AlignLeft | Qt.AlignVCenter
                    text: positionSlider.value.toFixed(0) + "/" + positionSlider.to
                }
                Component {
                    id: component_servoSettingsButton
                    Button{
                        id: servoSettingsButton
                        flat: true
                        contentItem: Image {
                            fillMode: Image.Pad
                            horizontalAlignment: Image.AlignHCenter
                            verticalAlignment: Image.AlignVCenter
                            source: "qrc:/images/+material/settings.svg"
                            sourceSize.width: 32
                            sourceSize.height: 32
                            opacity: 0.50
                        }
                        onClicked: {
                            mainStack.servoToEdit = index
                            mainStack.push("qrc:/ServoSettingsPage.qml")
                        }
                    }
                }
                Loader {
                    id: loader_servoSettingsButton
                    Layout.column: 1
                    Layout.row:0
                    Layout.rowSpan: 2
                    Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
                    Layout.maximumWidth: newServo.width / 7
                    sourceComponent: component_servoSettingsButton
                }
 
            }
            Rectangle{
                x: -16
                width: 6
                height: newServo.height + 16
                anchors.bottom: listDivider.bottom
                color: scolor
            }
 
            Rectangle{
                id: listDivider
                width: servoControlPage.width
                height: 1
                anchors{top: servoControllerLayout.bottom; topMargin: 8}
                color: "#000000"
                opacity: 0.12
            }
        }
        model: servoListModel
    }
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
26.11.2016, 17:28
Помогаю со студенческими работами здесь

Ошибка при наследование фрейма: Error creating form: Ancestor for '.' not found
Здравствуйте! Имеется модуль BaseForms, в котором описан класс, наследуемый от TFrame: TMyFrame = class(TFrame) ... end; Далее...

Maven-shade-plugin (Error creating shaded jar: error in opening zip file)
Доброго времени суток! Помогите, пожалуйста, понять в чем может быть причина ошибок сборки fat-jar архива. pom.xml: &lt;?xml...

Error while creating table 2055: Lost connection to MySQL server at 'localhost:3306', system error
Доброго времени суток. Сейчас реализовываю БД для приложения. Ничего не предвещало беды ровно до тех пор пока я не получил ошибку в...

QML Type error при закрытии
Доброго времени суток, есть код: ListView { anchors.fill: parent; model: engine.datas delegate:...

Error creating bean with name 'getSessionFactory'
весь стектрейс проглядел но не понял на что именно ошибка понятно что nullpointer но не вижу на что именно


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
Новый CodeBlocs. Версия 25.03
palva 04.01.2026
Оказывается, недавно вышла новая версия CodeBlocks за номером 25. 03. Когда-то давно я возился с только что вышедшей тогда версией 20. 03. С тех пор я давно снёс всё с компьютера и забыл. Теперь. . .
Модель микоризы: классовый агентный подход
anaschu 02.01.2026
Раньше это было два гриба и бактерия. Теперь три гриба, растение. И на уровне агентов добавится между грибами или бактериями взаимодействий. До того я пробовал подход через многомерные массивы,. . .
Учёным и волонтёрам проекта «Einstein@home» удалось обнаружить четыре гамма-лучевых пульсара в джете Млечного Пути
Programma_Boinc 01.01.2026
Учёным и волонтёрам проекта «Einstein@home» удалось обнаружить четыре гамма-лучевых пульсара в джете Млечного Пути Сочетание глобально распределённой вычислительной мощности и инновационных. . .
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru