Alex
AlexFeb. 6, 2018, 1:59 p.m.

QML TableView выравнивание колонки под размер контента

TableView, TableViewColumn

Добрый день. Помогите пожалуйста, наставьте в каком направлении копать. Парсер для сайта пишу. Я из с++ слоя передаю в QML данные. Данные ловлю через сигнал и потом передаю данные в таблицу. Подскажите пожалуйста как правильно работать с таблицей чтобы её колонки автоматически адаптировались под ширину контента. Ниже привожу код. Я нашёл свойство void resizeColumnsToContents() для TableView, устанавливал его в разных местах кода но результата никакого. Спасибо за помощь откликнувшимся.


import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtGraphicalEffects 1.0
import QtQuick.Window 2.2
import QtQuick.Layouts 1.3
import QtQuick.Controls.Styles 1.4

ApplicationWindow {
    id: rootWindow
    visible: true
    width: Screen.desktopAvailableWidth / 1.5
    height: Screen.desktopAvailableHeight / 1.5
    title: qsTr("Analytics Window")

    Connections {
        target: informationData

        onSigListTransactionSelectedCurrency: {
            modelInformationData.clear()
            for(var i = 0; i < data_1.length; i++)
            {
                modelInformationData.append( { Amnt_base:data_1[i].toString(), Amnt_trade:data_2[i].toString(), Price:data_3[i].toString() + " UAH", Pub_date:data_4[i].toString(), User:data_5[i].toString(), Type:data_6[i].toString() } )
            }
        }

        // Sell
        onSigListSellSelectedCurrency: {
            modelSellListCurrency.clear()

            textMinPrice.text = "Минимальная цена: " + "<font size='15' color='yellow'>" + data_1[0].toFixed(10) + "</font>"
            textSellTotal.text = "Всего: " + "<font size='15' color='yellow'>" + data_1[1].toFixed(10) + "</font>"
            textMaxPrice.text = "Максимальная цена: " + "<font size='15' color='yellow'>" + data_1[2].toFixed(10) + "</font>"

            for(var j = 0; j < data_2.length; j++)
            {
                modelSellListCurrency.append( { currency_trade: data_2[j].toFixed(10) + "999999999999999999999" , price: data_3[j].toFixed(10), currency_base: data_4[j].toFixed(10) } )
            }
        }

        // Buy
        onSigListBuySelectedCurrency: {
            modelBuyListCurrency.clear()

            textMinPriceBuy.text = "Минимальная цена: " + "<font size='15' color='yellow'>" + data_1[0].toFixed(10) + "</font>"
            textBuyTotal.text = "Всего: " + "<font size='15' color='yellow'>" + data_1[1].toFixed(10) + "</font>"
            textMaxPriceBuy.text = "Максимальная цена: " + "<font size='15' color='yellow'>" + data_1[2].toFixed(10) + "</font>"

            for(var j = 0; j < data_2.length; j++)
            {
                modelBuyListCurrency.append( { currency_trade: data_2[j].toFixed(10), price: data_3[j].toFixed(10), currency_base: data_4[j].toFixed(10) } )
            }
        }
    }


    // Models;
    ListModel {
        id: modelInformationData
    }

    ListModel {
        id: modelSellListCurrency
    }

    ListModel {
        id: modelBuyListCurrency
    }

    TextMetrics {
        id: textMetrics
    }
    // Elements;
    RowLayout {
        anchors.fill: parent

        Rectangle {
            width: parent.width
            height: parent.height

            LinearGradient {
                anchors.fill: parent
                start: Qt.point(0, 0)
                end: Qt.point(0, 300)
                gradient: Gradient {
                    GradientStop { position: 0.0; color: "#696969" }
                    GradientStop { position: 1.0; color: "#A9A9A9" }
                }
            }

            RowLayout {
                anchors.right: parent.right
                spacing: 10
                y: 10

                Button {
                    id: btnGetData
                    text: "Получить данные"

                    onClicked: {
                        informationData.getCurrencyDataFromSite(cbCurrency.currentText)
                    }
                }

                Button {
                    id: btnExit
                    text: "Выход"

                    onClicked: {
                        close()
                    }
                }
                ComboBox {
                    id: cbCurrency
                    model: informationData.getFromSiteCurrencies()
                    width: 200
                    height: btnGetData.height
                }
            }

            // Sell section;
            ColumnLayout {
                y: 10
                x: 10
                Text {
                    text: "Заявки на продажу"
                    color: "blue"
                    font.pointSize: 13
                    font.underline: true
                }

                Text {
                    id: textSellTotal
                    text: "Всего:"
                    color: "black"
                    font.bold: true
                }
                Text {
                    id: textMinPrice
                    text: "Минимальная цена:"
                    color: "black"
                    font.bold: true
                }
                Text {
                    id: textMaxPrice
                    text: "Максимальная цена:"
                    color: "black"
                    font.bold: true
                }
            }

            TableView {
                id: tableListSell
                x: 10
                y: textMaxPrice.y + 30
                //width: buyColumn_1.width + buyColumn_2.width + buyColumn_3.width
                height: rootWindow.height / 4
                onContentItemChanged: tableListSell.resizeColumnsToContents()


                TableViewColumn {
                    id: sellColumn_1
                    role: "price"
                    title: "Цена за еденицу"
                }
                TableViewColumn {
                    id: sellColumn_2
                    role: "currency_trade"
                    title: "Количество"
                }
                TableViewColumn {
                    id: sellColumn_3
                    role: "currency_base"
                    title: "Сумма"
                }
                model: modelSellListCurrency
                Component.onCompleted: {
                    tableListSell.width = sellColumn_1.width + sellColumn_2.width + sellColumn_3.width
                }
            }

            // Buy section;

            ColumnLayout {
                y: 10
                x: tableListSell.width + 50
                Text {
                    text: "Заявки на покупку"
                    color: "blue"
                    font.pointSize: 13
                    font.underline: true
                }

                Text {
                    id: textBuyTotal
                    text: "Всего:"
                    color: "black"
                    font.bold: true
                }
                Text {
                    id: textMinPriceBuy
                    text: "Минимальная цена:"
                    color: "black"
                    font.bold: true
                }
                Text {
                    id: textMaxPriceBuy
                    text: "Максимальная цена:"
                    color: "black"
                    font.bold: true
                }
            }

            TableView {
                id: tableListBuy
                x: tableListSell.width + 50
                y: textMaxPrice.y + 30
                height: rootWindow.height / 4

                TableViewColumn {
                    id: buyColumn_1
                    role: "price"
                    title: "Цена за еденицу"
                }
                TableViewColumn {
                    id: buyColumn_2
                    role: "currency_trade"
                    title: "Количество"
                }
                TableViewColumn {
                    id: buyColumn_3
                    role: "currency_base"
                    title: "Сумма"
                }

                model: modelBuyListCurrency
                Component.onCompleted: {
                    tableListBuy.width = buyColumn_1.width + buyColumn_2.width + buyColumn_3.width
                }
            }
        }
    }
}

table.png
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

2
Evgenii Legotckoi
  • Feb. 6, 2018, 5:43 p.m.

Добрый день!

Вообще, метод resizeColumnsToContents() на самом деле работает. Добавьте в проект дополнительную кнопочку, которая будет вызывать этот метод.

Button {
    id: btnCheckColumnsResize
    text: "Columns Resize"

    onClicked: {
        tableListSell.resizeColumnsToContents()
    }
}
Вопрос действительно в последовательности вызовов метода. Я бы попробовал вызывать этот метод каждый раз, когда модель данных будет полностью заполнена и установлена в таблицу. Тогда эффект должен иметь место.
    Alex
    • Feb. 7, 2018, 7:05 a.m.

    Спасибо большое за помощь, в который раз выручаете. Вы были правы. Вышел из ситуации по сигналу TableView = onRowCountChanged, после изменений мы обновляем размеры таблицы.

      TableView {
                    id: tableListBuy
                    x: tableListSell.width + 80
                    y: textMaxPrice.y + 30
                    height: rootWindow.height / 4
    
                    TableViewColumn {
                        id: buyColumn_1
                        role: "price"
                        title: "Цена за еденицу"
                    }
                    TableViewColumn {
                        id: buyColumn_2
                        role: "currency_trade"
                        title: "Количество"
                    }
                    TableViewColumn {
                        id: buyColumn_3
                        role: "currency_base"
                        title: "Сумма"
                    }
    
                    model: modelBuyListCurrency
    
                    Component.onCompleted: {
                        tableListBuy.width = buyColumn_1.width + buyColumn_2.width + buyColumn_3.width
                    }
    
                    onRowCountChanged: {
                        tableListBuy.resizeColumnsToContents()
                        tableListBuy.width = buyColumn_1.width + buyColumn_2.width + buyColumn_3.width + 5
                    }
                }
    

      Comments

      Only authorized users can post comments.
      Please, Log in or Sign up
      e
      • ehot
      • March 31, 2024, 9:29 p.m.

      C++ - Тест 003. Условия и циклы

      • Result:78points,
      • Rating points2
      B

      C++ - Test 002. Constants

      • Result:16points,
      • Rating points-10
      B

      C++ - Test 001. The first program and data types

      • Result:46points,
      • Rating points-6
      Last comments
      k
      kmssrFeb. 9, 2024, 2:43 a.m.
      Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
      Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
      EVA
      EVADec. 25, 2023, 6:30 p.m.
      Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
      J
      JonnyJoDec. 25, 2023, 4:38 p.m.
      Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
      G
      GvozdikDec. 19, 2023, 5:01 a.m.
      Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
      Now discuss on the forum
      DA
      Dr Gangil AcademicsApril 20, 2024, 2:45 p.m.
      Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
      a
      a_vlasovApril 14, 2024, 1:41 p.m.
      Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
      Павел Дорофеев
      Павел ДорофеевApril 14, 2024, 9:35 a.m.
      QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
      f
      fastrexApril 4, 2024, 11:47 a.m.
      Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

      Follow us in social networks