QT QStringListModel 示例代码

1.  QStringListModel , 实现 插入 删除 编辑 list,支持鼠标双击编辑。 

 

2. dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QtGui>

class Dialog : public QDialog
{
    Q_OBJECT
    
public:
    Dialog(const QStringList &leaders, QWidget *parent = 0);

public slots:
    void insertName();
    void deleteName();
    void editName();

private:
    QListView *listView;
    QStringListModel *model;

};

#endif // DIALOG_H


 

dialog.cpp

#include "dialog.h"
#include <QtGui>

Dialog::Dialog(const QStringList &leaders,QWidget *parent)
    : QDialog(parent)
{
    model = new QStringListModel;
    model->setStringList(leaders);

    listView = new QListView;
    listView->setModel(model);

    QPushButton *insertButton = new QPushButton(tr("insert"));
    QPushButton *deleteButton = new QPushButton(tr("delete"));
    QPushButton *editButton = new QPushButton(tr("edit"));
    connect(insertButton, SIGNAL(clicked()), this, SLOT(insertName()));
    connect(deleteButton, SIGNAL(clicked()), this, SLOT(deleteName()));
    connect(editButton, SIGNAL(clicked()), this, SLOT(editName()));

    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->addWidget(insertButton);
    hLayout->addWidget(deleteButton);
    hLayout->addWidget(editButton);
    QVBoxLayout *vLayout = new QVBoxLayout;
    vLayout->addWidget(listView);
    vLayout->addLayout(hLayout);

    setLayout(vLayout);
}

void Dialog::insertName()
{
    bool ok;
    QString name = QInputDialog::getText(this, tr("New Name"), tr(""),
                                         QLineEdit::Normal, tr(""), &ok );
    if( ok && !name.isEmpty() )
    {
        int row = listView->currentIndex().row();
        model->insertRows(row,1);
        QModelIndex index = model->index(row);
        model->setData(index, name);
        listView->setCurrentIndex(index);
    }
}

void Dialog::deleteName()
{
    model->removeRows(listView->currentIndex().row(), 1);
}

void Dialog::editName()
{
    int row = listView->currentIndex().row();
    QModelIndex index = model->index(row);
    QVariant variant = model->data(index, Qt::DisplayRole);
    QString name = variant.toString();
    bool ok;
    name = QInputDialog::getText(this, tr("Edit name"), tr(""), QLineEdit::Normal, tr(""), &ok);
    if( ok && !name.isEmpty() )
    {
        row = listView->currentIndex().row();
        index = model->index(row);
        model->setData(index, name);
        listView->setCurrentIndex(index);
    }
}

 

main.cpp

#include "dialog.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QStringList leaders;
    leaders << "test1" << "test2" << "test3" ;
    Dialog w(leaders);
    w.show();
    
    return a.exec();
}



 

posted @ 2013-08-20 11:07  今晚打酱油_  阅读(443)  评论(0编辑  收藏  举报