使用QtQuick.Controls 2单击QML TableView获取行

我在网上搜索了很多东西,但是没有找到答案,这真的很奇怪,因为我认为它是大多数人都应该使用的基本功能(可能我不明白如何正确地将TableViewQtQuick.Controls 2配合使用。)。

问题是:我想知道我单击了哪一行,并且想访问该行特定列的数据(类似TableView.get(row,column))。QtQuick.Controls 1.4中,有一些函数可以让我访问行(像这样),但是我找不到QtQuick.Control 2的行也没有选择:itemDelegate:会很有用。如何在QtQuick.Controls 2中实现这些东西

我在MinGw上使用Qt 5.15.0。我有来自数据库的数据,这些数据通过QAbstractTableModel传递给QML

.cpp模型

#include "archiviosqlmodel.h"
#include <QSqlRecord>
#include <QSqlError>
#include <QSqlQuery>
#include <QDebug>

ArchivioSqlModel::ArchivioSqlModel(QObject *parent) :
    QAbstractTableModel(parent)
{
    db_4= QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), "def.db");
        db_4.setDatabaseName("def.db");
    if (!db_4.isOpen())
        db_4.open();

    QSqlQuery query(db_4);
    query.exec("CREATE TABLE IF NOT EXISTS A (ID INTEGER PRIMARY KEY AUTOINCREMENT, B INTEGER, C CHAR(5), D CHAR(5), E CHAR(5));");
    query.exec("INSERT INTO A (ID, B, C, D, E) VALUES (1, 2, 'AAAAA', 'BBBBB', 'CCCCC')");
    query.exec("INSERT INTO A (ID, B, C, D, E) VALUES (2, 4, 'DDDDD', 'FFFFF', 'QQQQQ')");
    query.exec("INSERT INTO A (ID, B, C, D, E) VALUES (3, 5, 'EEEEE', 'GGGGG', 'HHHHH')");


    model.setQuery("SELECT * FROM A", db_4);

    qDebug() << "Row Count " << model.rowCount() << "Column count " << model.columnCount();
}

ArchivioSqlModel::~ArchivioSqlModel()
{
    db_4.close();
}

QVariant ArchivioSqlModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role == Qt::DisplayRole)
    {
        if(orientation == Qt::Horizontal)
        {
            switch (section)
            {
            case 0:
                return tr("ID");
            case 1:
                return tr("A");
            case 2:
                return tr("A");
            case 3:
                return tr("A");
            case 4:
                return tr("A");
            }
        }
    }
    return QVariant();
}

int ArchivioSqlModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return model.rowCount();
}

int ArchivioSqlModel::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return model.columnCount();
}

QVariant ArchivioSqlModel::data(const QModelIndex &index, int role) const
{
    QVariant value;
    if (!index.isValid())
        return QVariant();
    if(role == Qt::DisplayRole && index.row() >= 0 && index.row() < rowCount()
            && index.column() >= 0 && index.column() < columnCount())
    {
        QModelIndex modelIndex = this->index(index.row(), index.column());
        value = model.data(modelIndex, Qt::DisplayRole);
        return value;//QString("data %1-%2").arg(index.row()).arg(index.column());
    }
    return QVariant();
}

.h模型

    #include <QSqlQueryModel>


class ArchivioSqlModel : public QAbstractTableModel
{
    Q_OBJECT

public:
    explicit ArchivioSqlModel(QObject *parent = 0);

    Q_INVOKABLE QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    ~ArchivioSqlModel() override;

signals:
    void queryStrChanged();

public slots:

private:
    const static char* COLUMN_NAMES[];
    const static char* SQL_SELECT;

    QSqlDatabase db_4;
    QSqlQueryModel model;

    QHash<int, QByteArray> m_roleNames;

};

main.qml

 import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.4
import Archive 1.0
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    Rectangle {
        id: rectangle
        x: 62
        y: 106
        width: 200
        height: 200
        color: "#000022"
        border.width: 0
        anchors.fill:parent

        Rectangle {
            id: rectangleBack
            x: 10
            y: 406
            width: 64
            height: 64
            color: "#000033"
            radius: 20
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 10
            border.width: 2
            border.color: "#ffffff"

            MouseArea {
                id: mouseAreaBack
                anchors.fill: parent
                onClicked: {
                    if (stackView.depth > 1)
                        stackView.pop()
                }
                onPressed: {
                    rectangleBack.width = 64 - 4
                    rectangleBack.height = 64 - 4
                }
                onReleased: {
                    rectangleBack.width = 64
                    rectangleBack.height = 64
                }
            }
        }

        Text {
            id: textArchive
            height: 25
            color: "#ffffff"
            text: qsTr("Datas:")
            font.family: "Arial"
            verticalAlignment: Text.AlignVCenter
            font.bold: true
            fontSizeMode: Text.Fit
            horizontalAlignment: Text.AlignHCenter
            anchors.right: parent.right
            anchors.rightMargin: 0
            anchors.left: parent.left
            anchors.leftMargin: 0
            anchors.top: parent.top
            anchors.topMargin: 10
            font.pixelSize: 14
        }

        ArchivioSqlModel {
            id: archiviomodel
        }

        Rectangle {
            id: rectangle1
            color: "#000022"
            radius: 10
            border.width: 2
            border.color: "#ffffff"
            anchors.right: parent.right
            anchors.rightMargin: 5
            anchors.left: parent.left
            anchors.leftMargin: 5
            anchors.bottom: rectangleBack.top
            anchors.bottomMargin: 10
            anchors.top: textArchive.bottom
            anchors.topMargin: 10

            TableView {
                id: tableViewid
                anchors.leftMargin: 5
                anchors.bottomMargin: 5
                anchors.rightMargin: 5
                anchors.topMargin: 5

                columnWidthProvider: function (column) { return 100; }
                rowHeightProvider: function (column) { return 60; }
                anchors.fill: parent
                topMargin: columnsHeader.implicitHeight



                model: archiviomodel
                ScrollBar.horizontal: ScrollBar{}
                ScrollBar.vertical: ScrollBar{}
                clip: true



                delegate: Rectangle {
                    Text {
                        id: textId
                        text: display
                        anchors.fill: parent
                        anchors.margins: 10
                        color: 'black'
                        font.pixelSize: 15
                        verticalAlignment: Text.AlignVCenter
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            console.log("prova:" + textId.text)
                        }
                    }
                }


                Rectangle { // mask the headers
                    z: 3
                    color: "#000033"
                    y: tableViewid.contentY
                    x: tableViewid.contentX
                    width: tableViewid.leftMargin
                    height: tableViewid.topMargin
                }

                Row {
                    id: columnsHeader
                    y: tableViewid.contentY
                    z: 2
                    Repeater {
                        model: tableViewid.columns > 0 ? tableViewid.columns : 1
                        Label {
                            width: tableViewid.columnWidthProvider(modelData)
                            height: 35
                            text: archiviomodel.headerData(modelData, Qt.Horizontal)
                            color: '#ffffff'
                            font.pixelSize: 15
                            padding: 10
                            verticalAlignment: Text.AlignVCenter

                            background: Rectangle {
                                radius: 10
                                color: "#000022"
                            }
                        }
                    }
                }

                ScrollIndicator.horizontal: ScrollIndicator { }
                ScrollIndicator.vertical: ScrollIndicator { }

            }
        }

        Rectangle {
            id: rectangleOpenlap
            x: 10
            y: 406
            width: 64
            height: 64
            color: "#000033"
            radius: 20
            anchors.right: parent.right
            anchors.rightMargin: 10
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 10
            border.width: 2
            border.color: "#ffffff"

            MouseArea {
                id: mouseAreaOpenlap
                anchors.fill: parent
                onClicked: {
                    console.log("Rows")
                }
                onPressed: {
                    rectangleOpenlap.width = 64 - 4
                    rectangleOpenlap.height = 64 - 4
                }
                onReleased: {
                    rectangleOpenlap.width = 64
                    rectangleOpenlap.height = 64
                }
            }
        }
    }
}

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "archiviosqlmodel.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    qmlRegisterType<ArchivioSqlModel>("Archive", 1, 0, "ArchivioSqlModel");

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

提前致谢!

米奇

要从模型访问数据,可以使用模型上下文属性和内置的显示角色

MouseArea {
    anchors.fill: parent
    onClicked: {
        console.log(model.display)
    }
}

可以以类似方式设置模型数据

上面基本上是下面的简短方法:

MouseArea {
    anchors.fill: parent
    onClicked: {
        console.log(row, column, tableViewid.model.data(tableViewid.model.index(row, column)))
    }
}

上面的代码使用index()创建一个索引,然后可以将其传递给data()

行和列属性提供给每个委托

如果出于某种原因需要从委托外部从模型中获取数据,这也很有用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法使用jQuery获取.attr('aria-controls')

QtQuick TableView不能与C ++-QAbstractTableModel一起使用

javafx tableview如何获取我单击的行?

QtQuick Controls 2中的菜单栏

Qt Quick Controls 2和TableView

如何在QtQuick Controls 2中将屏幕上的对话框居中?

QtQuick.Controls 2.2中的QML组合框样式问题

无法与Pyside 2一起使用QtQuick Controls 2

如何更改QML Button Qt Quick Controls 2的背景颜色?

如何在单击QtQuick2 TableView时获得列号

QML TextArea:使用QtQuick.Controls> 2.0和1.4时的行为不同

QML:委托Choice中的ComboBox无法从Controls 2 tableView模型读取值。(model.display未定义)

来自C ++的QStandardItemModel在QtQuick / QML TableView中不可见

QtQuick.Controls 2.12不在按钮上显示焦点

MenuBar QML QtQuick.Controls 1.0

错误:“未安装模块“ QtQuick.Controls”

导入QtQuick.Controls 2.1 QML模块未找到

在单元格按钮上单击以获取tableview行

如何使用QtQuick ListView在onCurrentItemChanged中获取模型

QtQuick.Controls 2 StackView和destroyOnPop

QtQuick.Controls 2.0无法接受ApplicationWindow的宽度/高度

使用 QtQuick.Controls 2.1 找不到 Qt QML SpinBox minimumValue

QtQuick Controls 2 的默认键盘交互是如何指定的?

使用 QML 材料设计时遇到问题:未安装“QtQuick.Controls.Material”

Qt - 未安装模块“QtQuick.Controls”

使用 QtQuick.Controls 1.12 将 Qt TextTable 与 TextArea 一起使用时,文本会错位

如何使用 QML 中的 TableView 从 QtQuickControls 1 获取列数据?

QT5:未找到 QTQuick.Controls 2.12 版

如何在 TableView QtQuick.Controls 2.4 中实现 TableView QtQuick.Controls 1.4 的 Selectable future