精华内容
下载资源
问答
  • qml tableview

    2020-12-07 21:47:33
    tableview的排序功能,qt官方示例有,可以參考做,qt官方实例如下: Qt Quick Controls 1 - Table View Example QML type registration: #include <QtQml/qqml.h> ... qmlRegisterType<...

    tableview的排序功能,qt官方示例有,可以參考做,qt官方实例如下:

    Qt Quick Controls 1 - Table View Example

    QML type registration:

     #include <QtQml/qqml.h>
     ...
     qmlRegisterType<SortFilterProxyModel>("org.qtproject.example", 1, 0, "SortFilterProxyModel");
     ...

    QML namespace import:

     import org.qtproject.example 1.0

    主要是使用SortFilterProxyModel实现表头排序功能

     

    关于tableview右键点击功能,qt quick control 1.4没有支持,只有onClicked事件,只支持鼠标左键,

    可以修改源码加上右键点击事件,这里就不细说了,就是仿照qt源码里面的clicked事件,左右一个

    类似与rightClicked事件就可以触发右键点击功能了

     

    关于表头支持复选框的功能可以自定义实现,不如可以使用一个Rectangle覆盖表头第一个Column,

    做一个checkButton,再与tableView里面的数据列表关联就可以了,可以使用类似这样的自定义功能

    目前暂时没有看到qt自己支持表头第一column有复选功能,所以可以采用这样的自定义实现

    展开全文
  • QmlTableView

    千次阅读 2017-10-19 17:34:41
    rowCount 获取总行数 columnCount 获取总列数 data 获取当前数据 roleNames mvc别名 Qml中: QmlTableView{ id: qmlTableView height: frmWindow.height - 40 width: parent.width tableView.itemDelegate:Rectangle...

    使用QtQuick的MVC模式
    新建c++类继承于QAbstractTableModel, 并实现几个重要方法:

    CPP中:

    class QmlTableViewModel : public QAbstractTableModel
    {
        Q_OBJECT
    public:
        explicit QmlTableViewModel();
        int rowCount(const QModelIndex & parent = QModelIndex()) const Q_DECL_OVERRIDE;
        int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
        QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
        QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE;
    
        Q_INVOKABLE void Add(QString one, QString two, QString three);
        Q_INVOKABLE void Set(int row, int column, QString text);
        Q_INVOKABLE void Del();
        Q_INVOKABLE void Refresh();
    private:
       QVector<QVector<QString>> m_aryData;
    };
    

    注册c++类:

        QmlTableViewModel model;
        engine.rootContext()->setContextProperty("theModel", &model);
    

    rowCount 获取总行数
    columnCount 获取总列数
    data 获取当前数据
    roleNames mvc别名

    Qml中:

        QmlTableView{
            id: qmlTableView
            height: frmWindow.height - 40
            width: parent.width
            tableView.itemDelegate:Rectangle {
                TextField{
                    id: textField
                    height: 25
                    text: styleData.value
                    selectByMouse: true
                    onEditingFinished: {
                        theModel.Set(styleData.row, styleData.column, textField.text);
                    }
                    visible: (styleData.column !== 0)
                }
                Image{
                    id: image
                    height: 25
                    width: 25
                    source: "qrc:/Face.png"
                    visible: (styleData.column === 0)
                }
            }
            tableView.rowDelegate: Rectangle {
                height: 25
            }
        }
    

    在这里插入图片描述

    需要完整代码请访问QtQuickExamples

    联系方式:


    作者郑天佐
    QQ278969898
    主页http://www.camelstudio.cn
    邮箱camelsoft@163.com
    博客http://blog.csdn.net/zhengtianzuo06
    githubhttps://github.com/zhengtianzuo
    QQ群199672080

    在这里插入图片描述

    觉得分享的内容还不错, 就请作者喝杯咖啡吧~~

    展开全文
  • QML TableView编辑使用

    2021-04-12 14:33:48
    相关文章 1、QML TableView使用----http://www.cppblog.com/gaimor/archive/2019/09/06/216784.html...2、qml TableView样式设置----https://blog.csdn.net/jueying6449/article/details/86147330?utm_medium=distrib

    原文地址::https://blog.csdn.net/chyuanrufeng/article/details/79902128

    相关文章

    1、QML TableView使用----http://www.cppblog.com/gaimor/archive/2019/09/06/216784.html

    2、qml TableView样式设置----https://blog.csdn.net/jueying6449/article/details/86147330?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-3.control&dist_request_id=&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-3.control

    3、QmlTableView----https://blog.csdn.net/zhengtianzuo06/article/details/78287450?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_baidulandingword-0&spm=1001.2101.3001.4242

    4、qml 表格TableView 创建----https://blog.csdn.net/sy_18244244951/article/details/105455969?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-5.control&dist_request_id=&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-5.control

     

    在开发中,表格使用还是很频繁的。qt例子中的比较丑,行高不能修改。本例QML实现动态表头、添加数据,自定义样式,修改行高,在c++中动态添加数据等。

    具体效果如下:

    核心代码TableViewItem.qml

    import QtQuick 2.6
    import QtQuick.Window 2.2
    import QtQuick.Controls 1.4
    import QtQuick.Controls.Styles 1.4
     
    Item {
        //anchors.centerIn: parent
        width: 500; height: 400
     
        //[add header]
        function addColunm(rolorstr, titlestr)
            {
     
                var prefix = 'import QtQuick 2.7;import QtQuick.Controls 1.4;TableViewColumn {width: tableView.viewport.width/tableView.columnCount;';
                //创建TableViewColumn的代码
                //循环添加TableViewColumn
                var str = prefix  +"role:\"" + rolorstr + "\";title:\"" + titlestr + "\"}";
                tableView.addColumn(Qt.createQmlObject(str,tableView,"qrc:/TableViewItem.qml"));
            }
        //[!add header]
     
        //[addrowdata]
        function addRowData(d)
        {
             tablemode.append(d);
        }
        //[!addrowdata]
     
        /
        ListModel {
            id: tablemode
     
            ListElement {
                title: "A"
                author: "Gabriel"
            }
            ListElement {
                title: "Brilliance"
                author: "Jens"
            }
            ListElement {
                title: "Outstanding"
                author: "Frederik"
            }
        }
     
        TableView{
            id :tableView
            anchors.fill: parent
            alternatingRowColors : false
            TableViewColumn {
                      role: "title"
                      title: "Title"
                      width: tableView.viewport.width/tableView.columnCount
                  }
              TableViewColumn {
                  role: "author"
                  title: "Author"
                  width: tableView.viewport.width/tableView.columnCount
              }
              model: tablemode
     
              //自定义表头代理
               headerDelegate:
               Rectangle{
                   //color: "#00498C"
                   gradient: Gradient {
                       GradientStop { position: 0.0; color: "#085FB2" }
                       GradientStop { position: 1.0; color: "#00498C" }
                   }
                   //color : styleData.selected ? "blue": "darkgray"
                   width: 100;
                   height: 40
                   border.color: "black"
                   //border.width: 1
                   //radius: 5
                   Text
                    {
                        anchors.centerIn : parent
                        text: styleData.value
                        font.pixelSize: parent.height*0.5
                    }
               }
     
           //行代理可以修改行高等信息
           rowDelegate: Rectangle {
               height: 50
               color: "#052641"
               anchors.leftMargin: 2
     
           }
           itemDelegate: Rectangle{
               //color: "#052641"
               border.width: 1
               color : styleData.selected ? "#dd00498C": "#052641"
               Text {
                    anchors.verticalCenter: parent.verticalCenter
                    //anchors.fill: parent
                    anchors.leftMargin: 5
                    color : styleData.selected ? "#00CCFE": "white"
                    text: styleData.value
                    font.pixelSize: parent.height*0.4
                }
           }
     
             style: TableViewStyle{
                 textColor: "white"
                 highlightedTextColor : "#00CCFE"  //选中的颜色
                 backgroundColor : "#052641"
             }
        }
    }
    使用方式
    import QtQuick 2.6
    import QtQuick.Window 2.2
    import QtQuick.Controls 1.4
    import QtQuick.Controls.Styles 1.4
    import QtQuick.Layouts 1.1
    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
        objectName: "root"
        color: "#0C1F31"
        Rectangle{
            width: 30; height: 30
            color: "blue";
            MouseArea{
                anchors.fill: parent
                onClicked: {
                    console.log(Date().toLocaleString(Qt.locale("de_DE")))
                    for (var i = 0; i < 10; ++i)
                        item.addRowData({title:"addd"+i ,author:"ts"});
                    //item.addColunm("s"+i,"d")
                    console.log(Date().toLocaleString(Qt.locale("de_DE")))
                }
                onWheel: {
                    if (wheel.angleDelta.y > 0)
                         item.scale = item.scale*1.2;
                     else
                         item.scale = item.scale*0.8;
                 }
            }
        }
        TableViewItem{
            id : item
            anchors.centerIn: parent
            objectName: "tableview"
            x : 30; y : 100
            //anchors.centerIn:  parent
        }
    }


    在c++中动态添加数据

     QQmlApplicationEngine engine;
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        if (engine.rootObjects().isEmpty())
            return -1;
       QQuickItem*  item = engine.rootObjects().at(0)->findChild<QQuickItem*>("tableview");
       qDebug() << item->objectName();
       QVariantMap m;
       m.insert("title","ssssxx");
       m.insert("author","ceshi");
       QMetaObject::invokeMethod(item,  "addRowData",  Q_ARG(QVariant, m)); //调用函数
    ————————————————
    版权声明:本文为CSDN博主「缘如风」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/chyuanrufeng/article/details/79902128

     

    展开全文
  • qml tableview 表格

    2021-01-06 03:52:54
    作者,QQ1284524409。 预览, deploy.pri HEADERS += \ $$PWD/deploy.h SOURCES += \ $$PWD/deploy.cpp  deploy.h #ifndef DEPLOY_H #define DEPLOY_H #include #include class Deploy : public ... void
  • I have TableView from Qml 2.0 controls that is connected to QAbstractItemModel. I want to make a context menu that can change the properties or simply call methods of a concrete object from the model....

    I have TableView from Qml 2.0 controls that is connected to QAbstractItemModel. I want to make a context menu that can change the properties or simply call methods of a concrete object from the model.

    Example:

    QAbstractItemModel has an std::vector. Person has a method alter() which makes some changes (any changes, it does not matter which ones exactly are changes, the point is that the we are able to call the method).

    When there is a right click on the row, the menu appears with an item Alter.

    All I was able to find is how to make the menu.

    rowDelegate: Item {

    Menu {

    id: myContextMenu

    MenuItem {text: "Alter"; onTriggered: {} }

    }

    MouseArea {

    id: longPressArea

    anchors.fill: parent

    acceptedButtons: Qt.LeftButton | Qt.RightButton

    onClicked: {

    if (mouse.button == Qt.RightButton)

    myContextMenu.popup()

    }

    }

    }

    But I still don't know how to connect the menu with an exact object of the row.

    解决方案

    Within the delegate, you can refer to the item by using the role.property convention.

    The default role would be display. Of course the Person has to derive from QObject, and must be registered with the QML Engine.

    The code below demonstrates how to:

    Create a sensibly behaving ObjectListModel for storage of QObjects, usable from QML.

    Create a QObject-derived class that keeps your data.

    Access the properties and invokable methods of the data objects from a pop-up menu shown on the delegate.

    The model can be set to automatically notify about changes to the properties of the contained QObjects. Such notifications, if resulting from bulk changes (say done in a loop) are coalesced and sent off as a single dataChanged event.

    Unfortunately, the user property of a QObject acquires no special meaning - you still need to use the .property selector to access it.

    Proper behavior of the model can be observed directly, since there are two lists hooked to the same model - they better showed the same thing.

    The ObjectListModel could also implement a mapping between the roles and the properties. Currently, both the display and edit roles select the entire object, not any particular property of it.

    If the storage of QObjects is too high of an overhead, an alternative model implementation could create QObject adapters to POD types on-the-fly.

    uUy4J.png

    main.cpp

    #include

    #include

    #include

    #include

    #include

    #include

    #include

    #include

    #include

    class Person : public QObject {

    Q_OBJECT

    Q_PROPERTY(QString name NOTIFY nameChanged MEMBER m_name)

    QString m_name;

    public:

    Q_INVOKABLE Person(QObject * parent = 0) : QObject(parent) { setRandomName(); }

    Q_INVOKABLE Person(QString name, QObject * parent = 0) :

    QObject(parent), m_name(name) {}

    Q_SIGNAL void nameChanged(const QString &);

    Q_INVOKABLE void setRandomName() {

    static const QString names = "Badger,Shopkeeper,Pepperpots,Gumbys,Colonel";

    static const QStringList nameList = names.split(',');

    QString newName = nameList.at(qrand() % nameList.length());

    if (newName != m_name) {

    m_name = newName;

    emit nameChanged(m_name);

    }

    }

    };

    class ObjectListModel : public QAbstractListModel {

    Q_OBJECT

    Q_DISABLE_COPY(ObjectListModel)

    //! Whether changes to underlying objects are exposed via `dataChanged` signals

    Q_PROPERTY(bool elementChangeTracking

    READ elementChangeTracking WRITE setElementChangeTracking

    NOTIFY elementChangeTrackingChanged)

    QObjectList m_data;

    std::function m_factory;

    bool m_tracking;

    QBasicTimer m_notifyTimer;

    QMap m_notifyIndexes;

    //! Updates the property tracking connections on given object.

    void updateTracking(QObject* obj) {

    const int nIndex = metaObject()->indexOfSlot("propertyNotification()");

    QMetaMethod const nSlot = metaObject()->method(nIndex);

    const int props = obj->metaObject()->propertyCount();

    if (m_tracking) for (int i = 0; i < props; ++i) {

    const QMetaProperty prop = obj->metaObject()->property(i);

    if (prop.hasNotifySignal()) connect(obj, prop.notifySignal(), this, nSlot);

    } else {

    disconnect(obj, 0, this, 0);

    }

    }

    //! Receives property notification changes

    Q_SLOT void propertyNotification() {

    int i = m_data.indexOf(sender());

    if (i >= 0) m_notifyIndexes.insert(i, 0);

    // All of the notifications will be sent as a single signal from the event loop.

    if (!m_notifyTimer.isActive()) m_notifyTimer.start(0, this);

    }

    protected:

    //! Emits the notifications of changes done on the underlying QObject properties

    void timerEvent(QTimerEvent * ev) {

    if (ev->timerId() != m_notifyTimer.timerId()) return;

    emit dataChanged(index(m_notifyIndexes.begin().key()),

    index((m_notifyIndexes.end()-1).key()),

    QVector(1, Qt::DisplayRole));

    m_notifyTimer.stop();

    m_notifyIndexes.clear();

    }

    public:

    //! A model that creates instances via a given metaobject

    ObjectListModel(const QMetaObject * mo, QObject * parent = 0) :

    QAbstractListModel(parent),

    m_factory([mo, this](){

    return mo->newInstance(Q_ARG(QObject*, this));

    }),

    m_tracking(false)

    {}

    //! A model that creates instances using a factory function

    ObjectListModel(const std::function & factory,

    QObject * parent = 0) :

    QAbstractListModel(parent), m_factory(factory), m_tracking(false)

    {}

    ~ObjectListModel() {

    qDeleteAll(m_data);

    }

    bool elementChangeTracking() const { return m_tracking; }

    void setElementChangeTracking(bool tracking) {

    if (m_tracking == tracking) return;

    for (QObject* obj : m_data) updateTracking(obj);

    emit elementChangeTrackingChanged(m_tracking = tracking);

    }

    Q_SIGNAL void elementChangeTrackingChanged(bool);

    int rowCount(const QModelIndex &) const Q_DECL_OVERRIDE {

    return m_data.count();

    }

    QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE {

    if (role == Qt::DisplayRole || role == Qt::EditRole) {

    return QVariant::fromValue(m_data.at(index.row()));

    }

    return QVariant();

    }

    bool setData(const QModelIndex &index, const QVariant &value, int role)

    Q_DECL_OVERRIDE {

    Q_UNUSED(role);

    QObject* object = value.value();

    if (!object) return false;

    if (object == m_data.at(index.row())) return true;

    delete m_data.at(index.row());

    m_data[index.row()] = object;

    emit dataChanged(index, index, QVector(1, role));

    return true;

    }

    Q_INVOKABLE bool insertRows(int row, int count,

    const QModelIndex &parent = QModelIndex())

    Q_DECL_OVERRIDE {

    Q_UNUSED(parent);

    beginInsertRows(QModelIndex(), row, row + count - 1);

    for (int i = row; i < row + count; ++ i) {

    QObject * object = m_factory();

    Q_ASSERT(object);

    m_data.insert(i, object);

    updateTracking(object);

    QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);

    }

    endInsertRows();

    return true;

    }

    Q_INVOKABLE bool removeRows(int row, int count,

    const QModelIndex &parent = QModelIndex())

    Q_DECL_OVERRIDE {

    Q_UNUSED(parent);

    beginRemoveRows(QModelIndex(), row, row + count - 1);

    while (count--) delete m_data.takeAt(row);

    endRemoveRows();

    return true;

    }

    };

    int main(int argc, char *argv[])

    {

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    qmlRegisterType();

    ObjectListModel model1(&Person::staticMetaObject);

    model1.setElementChangeTracking(true);

    model1.insertRows(0, 1);

    engine.rootContext()->setContextProperty("model1", &model1);

    engine.load(QUrl("qrc:/main.qml"));

    QObject *topLevel = engine.rootObjects().value(0);

    QQuickWindow *window = qobject_cast(topLevel);

    window->show();

    return app.exec();

    }

    #include "main.moc"

    main.qrc

    main.qml

    main.qml

    import QtQuick 2.0

    import QtQml.Models 2.1

    import QtQuick.Controls 1.0

    ApplicationWindow {

    width: 300; height: 300

    Row {

    width: parent.width

    anchors.top: parent.top

    anchors.bottom: row2.top

    Component {

    id: commonDelegate

    Rectangle {

    width: view.width

    implicitHeight: editor.implicitHeight + 10

    border.color: "red"

    border.width: 2

    radius: 5

    TextInput {

    id: editor

    anchors.margins: 1.5 * parent.border.width

    anchors.fill: parent

    text: edit.name // "edit" role of the model, to break the binding loop

    onTextChanged: {

    display.name = text; // set the name property of the data object

    }

    }

    Menu {

    id: myContextMenu

    MenuItem { text: "Randomize"; onTriggered: display.setRandomName() }

    MenuItem { text: "Remove"; onTriggered: model1.removeRows(index, 1) }

    }

    MouseArea {

    id: longPressArea

    anchors.fill: parent

    acceptedButtons: Qt.RightButton

    onClicked: myContextMenu.popup()

    }

    }

    }

    spacing: 2

    ListView {

    id: view

    width: (parent.width - parent.spacing)/2

    height: parent.height

    model: DelegateModel {

    id: delegateModel1

    model: model1

    delegate: commonDelegate

    }

    spacing: 2

    }

    ListView {

    width: (parent.width - parent.spacing)/2

    height: parent.height

    model: DelegateModel {

    model: model1

    delegate: commonDelegate

    }

    spacing: 2

    }

    }

    Row {

    id: row2

    anchors.bottom: parent.bottom

    Button {

    text: "Add Page";

    onClicked: model1.insertRows(delegateModel1.count, 1)

    }

    }

    }

    展开全文
  • qml mvc 使用checkbox全选、反选。TableViewColumn中添加代理checkbox在qml直接赋值会导致点击checkbox状态无法更新,本demo正好解决这个问题
  • TableView对应的数据model,使用Qml/ListModel,数据的创建、导入等操作,全部使用qml/js实现。 引入了JSONPath,快速访问JSON并转化到ListModel。 内容上有些汽车行业相关的文字,请忽略。 工程里面也有一些常用...
  • QML tableView表格自定义

    千次阅读 2020-05-29 14:32:52
    import QtQuick 2.12 import QtQuick.Controls 2.12 import Qt.labs.qmlmodels 1.0 Rectangle { z: 10 id: tableView width: dpH(919) height: dpH(475) anchors { top: parent.top .
  • TableView { anchors.fill: parent columnSpacing: 1 rowSpacing: 1 clip: true model: TableModel {} delegate: Rectangle { implicitWidth: 100 implicitHeight: 50 Text { text: display } } }
  • QML tableview样例学习

    2020-05-16 00:09:41
    路径\quickcontrols\controls\tableview /**代码 main.cpp**/ #include "qtquickcontrolsapplication.h" #include "sortfilterproxymodel.h" #include <QtQml/qqmlapplicationengine.h> #include <QtGui/...
  • QML TableView

    千次阅读 2018-04-17 18:08:11
    QML 写界面的时候,把自己坑了,不能正确的选中一行,最后发现第一列用了"index",这个可能是TableView的内置属性(猜测),后边给index赋值,所以不能选中争正确的行,换一个名字即可。TableView { x:...
  • Qt qml TableView 表格编辑器

    万次阅读 2017-08-03 11:21:28
    主要是为了展示如何用qml中的TableView控件制作一个表格编辑器。工程是从工作的项目里面单独扣出来的,内容上有些汽车行业相关的文字,请忽略。效果图:功能: 从特定格式JSON文件导入数据 从表格导出数据到JSON文件...
  • // Passing the same model to QML for displaying in the TableView. engine.rootContext()->setContextProperty ("SQQL", model); engine.load(QUrl(QStringLiteral("/home/.../main.qml"))); QObject *topLevel ...
  •  基于QML TableView(Qt 5.1)版本,内部滑动条样式修改 style: TableViewStyle { frame: Rectangle { color: "transparent" } //边框 incrementControl: Rectangle { color: "transparent" } //滑块 ...
  • qml TableView样式设置

    千次阅读 2019-01-09 13:35:02
    import QtQuick 2.9 import QtQuick.Window 2.2 import QtQuick.Controls 1.4 Window { visible: true width: 640 height: 480 title: qsTr("Hello World"... TableView { id: tableVi...
  • 基于qt 5.12版本自定义TableView 官方提供的没有标题,自定义添加标题栏 支持: 1.resize section 2.swap section 链接:github
  • qml TableView自定义属性

    2020-01-02 11:04:17
    TableView { id : mytableview width : mylistmode . width height : mylistmode . height model : mytablemodel TableViewColumn { role : "title" title : "老大" width : mytableview . ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 506
精华内容 202
关键字:

qmltableview