QTableView基本用法

来源:互联网 发布:现代软件学院毕业证 编辑:程序博客网 时间:2024/06/04 19:16
QTableView是Qt中用来把数据集以表格形式提供给用户的一个控件,它与C++Builder中的DBGrid作用类似。坦白的说,DBGrid的使用要比QTableView更容易一些。但QTableView在使用麻烦的同时,也提供了更多的灵活性。

  软件环境: ubuntu

  最终效果图:

  634868407862099609.jpg

  一、添加表头:
  1. QStandardItemModel *model = new QStandardItemModel();
  2. model->setColumnCount(2);
  3. model->setHeaderData(0,Qt::Horizontal,QString::fromLocal8Bit("卡号"));
  4. model->setHeaderData(1,Qt::Horizontal,QString::fromLocal8Bit("姓名"));
复制代码

  二、设置表格属性:
  1. ui->tableView->setModel(model);
  2. //表头信息显示居左
  3. ui->tableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
  4. //设置列宽不可变
  5. ui->tableView->horizontalHeader()->setResizeMode(0,QHeaderView::Fixed);
  6. ui->tableView->horizontalHeader()->setResizeMode(1,QHeaderView::Fixed);
  7. ui->tableView->setColumnWidth(0,101);
  8. ui->tableView->setColumnWidth(1,102);
复制代码

  注:在进行表格设置时必须是“ui->tableView->setModel(model);”在前,属性具体设置在后,

  反之则设置不会生效。如上述代码所示。

  三、添加行(添加三行一样的信息):
  1. for(int i = 0; i < 3; i++)
  2. {
  3.      model->setItem(i,0,new QStandardItem("2009441676"));
  4.         //设置字符颜色
  5.      model->item(i,0)->setForeground(QBrush(QColor(255, 0, 0)));
  6.         //设置字符位置
  7.      model->item(i,0)->setTextAlignment(Qt::AlignCenter);
  8.      model->setItem(i,1,new QStandardItem(QString::fromLocal8Bit("哈哈")));
  9. }
复制代码

  四、删除行:
  1. //x是指定删除哪一行
  2. model->removeRow(x);
  3. //删除所有行
  4. model->removeRows(0,model->rowCount());
复制代码

  再举一个例子:

  在一个药品划价模块中有这样的操作流程:

  检索处方项目成功后,把该项目显示到QTableView里,把需要编辑的数量字段提供给用户输入,用户输入确认后,该项目留在列表中,然后开始下一项目检索录入。

  实现过程如下:

  录入的项目保留在临时表tmp中,界面上的QTableView取名为tbList,与tbList关联的Model取名为tb1。检索成功后,把检索结果插入到临时表中,把需要编辑的字段提供给用户。
  1. tb1=newQSqlTableModel(this,*dbR); //dbR是本应用中的数据源
  2. tb1->setTable("tmp"); //处方临时表
复制代码

  程序中需要显示的时候,
  1. tbList->setModel(NULL); //清除原先数据集
  2. tbList->setModel(tb1); //刷新显示
复制代码

  程序中需要提供编辑输入的时候
  1. QModelIndexmdidx=m_ui->tbList->model()->index(row,column); //获得需要编辑的单元格的位置
  2. m_ui->tbList->setFocus(); //把输入焦点交给tbList
  3. m_ui->tbList->setCurrentIndex(mdidx); //设定需要编辑的单元格
  4. m_ui->tbList->edit(mdidx); //开始编辑
复制代码

  有一个问题需要注意。向QTableView中添加记录时,字段一定要完整,不能有空白字段,否则结果无法保存。切记。

  如果需要对用户输入做限制,比如只能在指定的字段输入指定的数据类型,可以通过QItemDelegate来实现。

  贴一段代码,说明QTableView基本用法
  1. QStandardItemModel model;
  2. //设置大小
  3. model.setColumnCount(3); //列
  4. model.setRowCount(musicFound); //行
  5. //设置标题
  6. model.setHeaderData(0,Qt::Horizontal,"ID");
  7. //添加数据
  8. for(int j=0;j<row;j++)
  9. {
  10.             //写id
  11.             QStandardItem *itemID = new QStandardItem("hello");//QString::number(j)));
  12.             model.setItem(j,0,itemID);
  13. }
  14. //选择这个model
  15. m_ui->tableView->setModel(&model);
  16. //隐藏左边那列
  17. m_ui->tableView->verticalHeader()->hide();
  18. //列宽
  19. m_ui->tableView->setColumnWidth(0,30);
  20. //整行选择
  21. m_ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

 

 

QT的MVC(View/Delegate)模型十分强大,可以利用各种控件来对表格的输入进行限制,不过我以前一直没有过,这几天研究了一下,写个小例子,希望大家喜欢。
 
如果看不懂这个例子,请先看QT的自带例子:http://qt-project.org/doc/qt-4.8/itemviews-spinboxdelegate.html
 
思路:
 
1:为每一列定义委托:
A:第一列是编号列,使用只读委托,令该列的单元格是只读的
B:第三列是ID列,只能输入1-12个数字,利用QLineEdit委托和正则表达式对输入进行限制
C:第四年龄列,利用QSpinBox委托进行输入限制,只能输入1-100之间的数字
D:第五列是性别列,利用QComboBox委托对输入进行限制,该列的单元格只能输入Male或Female
E:第六列是头像列,在该列的单元格中央放置一张头像
2:定义代理类,把所有单元格中的字符居中显示。
3:利用QSS,将表格的背景色弄成黄蓝相间。
 
截图:
 


上代码:
 1.#include <QtGui>  
 2. 
 3.//编号列,只读委托  
 4.//这个方法我还真想不到,呵呵  
 5.class ReadOnlyDelegate : public QItemDelegate 
 6.{ 
 7.    Q_OBJECT 
 8.public: 
 9.    ReadOnlyDelegate(QObject *parent = 0): QItemDelegate(parent) { } 
 10.    QWidget *createEditor(QWidget*parent, const QStyleOptionViewItem &option, 
 11.        const QModelIndex &index) const 
 12.    { 
 13.        return NULL; 
 14.    } 
 15.}; 
 16. 
 17.//ID列,只能输入1-12个数字  
 18.//利用QLineEdit委托和正则表达式对输入进行限制  
 19.class UserIDDelegate : public QItemDelegate 
 20.{ 
 21.    Q_OBJECT 
 22.public: 
 23.    UserIDDelegate(QObject *parent = 0): QItemDelegate(parent) { } 
 24.    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, 
 25.        const QModelIndex &index) const 
 26.    { 
 27.        QLineEdit *editor = new QLineEdit(parent); 
 28.        QRegExp regExp("[0-9]{0,10}"); 
 29.        editor->setValidator(new QRegExpValidator(regExp, parent)); 
 30.        return editor; 
 31.    } 
 32.    void setEditorData(QWidget *editor, const QModelIndex &index) const 
 33.    { 
 34.        QString text = index.model()->data(index, Qt::EditRole).toString(); 
 35.        QLineEdit *lineEdit = static_cast<QLineEdit*>(editor); 
 36.        lineEdit->setText(text); 
 37.    } 
 38.    void setModelData(QWidget *editor, QAbstractItemModel *model, 
 39.        const QModelIndex &index) const 
 40.    { 
 41.        QLineEdit *lineEdit = static_cast<QLineEdit*>(editor); 
 42.        QString text = lineEdit->text(); 
 43.        model->setData(index, text, Qt::EditRole); 
 44.    } 
 45.    void updateEditorGeometry(QWidget *editor, 
 46.        const QStyleOptionViewItem &option, const QModelIndex &index) const 
 47.    { 
 48.        editor->setGeometry(option.rect); 
 49.    } 
 50.}; 
 51. 
 52.//年龄列,利用QSpinBox委托进行输入限制,只能输入1-100之间的数字  
 53.class AgeDelegate : public QItemDelegate 
 54.{ 
 55.    Q_OBJECT 
 56.public: 
 57.    AgeDelegate(QObject *parent = 0): QItemDelegate(parent) { } 
 58.    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, 
 59.        const QModelIndex &index) const 
 60.    { 
 61.        QSpinBox *editor = new QSpinBox(parent); 
 62.        editor->setMinimum(1); 
 63.        editor->setMaximum(100); 
 64.        return editor; 
 65.    } 
 66.    void setEditorData(QWidget *editor, const QModelIndex &index) const 
 67.    { 
 68.        int value = index.model()->data(index, Qt::EditRole).toInt(); 
 69.        QSpinBox *spinBox = static_cast<QSpinBox*>(editor); 
 70.        spinBox->setValue(value); 
 71.    } 
 72.    void setModelData(QWidget *editor, QAbstractItemModel *model, 
 73.        const QModelIndex &index) const 
 74.    { 
 75.        QSpinBox *spinBox = static_cast<QSpinBox*>(editor); 
 76.        spinBox->interpretText(); 
 77.        int value = spinBox->value(); 
 78.        model->setData(index, value, Qt::EditRole); 
 79.    } 
 80.    void updateEditorGeometry(QWidget *editor, 
 81.        const QStyleOptionViewItem &option, const QModelIndex &index) const 
 82.    { 
 83.        editor->setGeometry(option.rect); 
 84.    } 
 85.}; 
 86. 
 87.//性别列,利用QComboBox委托对输入进行限制  
 88.//这一列的单元格只能输入Male或Female  
 89.class SexDelegate : public QItemDelegate 
 90.{ 
 91.    Q_OBJECT 
 92.public: 
 93.    SexDelegate(QObject *parent = 0): QItemDelegate(parent) { } 
 94.    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, 
 95.        const QModelIndex &index) const 
 96.    { 
 97.        QComboBox *editor = new QComboBox(parent); 
 98.        editor->addItem("Female"); 
 99.        editor->addItem("Male"); 
 100.        return editor; 
 101.    } 
 102.    void setEditorData(QWidget *editor, const QModelIndex &index) const 
 103.    { 
 104.        QString text = index.model()->data(index, Qt::EditRole).toString(); 
 105.        QComboBox *comboBox = static_cast<QComboBox*>(editor); 
 106.        int tindex = comboBox->findText(text); 
 107.        comboBox->setCurrentIndex(tindex); 
 108.    } 
 109.    void setModelData(QWidget *editor, QAbstractItemModel *model, 
 110.        const QModelIndex &index) const 
 111.    { 
 112.        QComboBox *comboBox = static_cast<QComboBox*>(editor); 
 113.        QString text = comboBox->currentText(); 
 114.        model->setData(index, text, Qt::EditRole); 
 115.    } 
 116.    void updateEditorGeometry(QWidget *editor, 
 117.        const QStyleOptionViewItem &option, const QModelIndex &index) const 
 118.    { 
 119.        editor->setGeometry(option.rect); 
 120.    } 
 121.}; 
 122. 
 123.//头像列,只是在单元格中央放一张小图而已  
 124.class IconDelegate : public QItemDelegate 
 125.{ 
 126.    Q_OBJECT 
 127.public: 
 128.    IconDelegate(QObject *parent = 0): QItemDelegate(parent) { } 
 129.    void paint(QPainter *painter, const QStyleOptionViewItem &option, 
 130.        const QModelIndex & index ) const 
 131.    { 
 132.        //show.bmp是在工程目录中的一张图片(其实就是QQ的图标啦,呵呵)  
 133.        QPixmap pixmap = QPixmap("show.bmp").scaled(24, 24); 
 134.        qApp->style()->drawItemPixmap(painter, option.rect,  Qt::AlignCenter, QPixmap(pixmap)); 
 135.    } 
 136.}; 
 137. 
 138.//代理类,把所有单元格中的字符居中显示  
 139.class VIPModel : public QStandardItemModel 
 140.{ 
 141.    Q_OBJECT 
 142.public: 
 143.    VIPModel(QObject *parent=NULL) : QStandardItemModel(parent) { } 
 144.    VIPModel(int row, int column, QObject *parent=NULL) 
 145.        : QStandardItemModel(row, column, parent) { } 
 146.    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const 
 147.    { 
 148.        if( Qt::TextAlignmentRole == role ) 
 149.            return Qt::AlignCenter;  
 150.        return QStandardItemModel::data(index, role); 
 151.    } 
 152. 
 153.}; 
 154. 
 155.#include "main.moc"  
 156. 
 157.int main(int argc, char *argv[]) 
 158.{ 
 159.    QApplication app(argc, argv); 
 160. 
 161.    VIPModel *model = new VIPModel(5, 5); 
 162.    QTableView *tableView = new QTableView; 
 163. 
 164.    //把表格的背景调成黄蓝相间  
 165.    //这种方法是在网上看到的,用起来还真方便啊  
 166.    tableView->setAlternatingRowColors(true); 
 167.    tableView->setStyleSheet("QTableView{background-color: rgb(250, 250, 115);" 
 168.        "alternate-background-color: rgb(141, 163, 215);}"); 
 169. 
 170.    tableView->setWindowTitle("VIP List"); 
 171.    tableView->resize(700, 400); 
 172.    tableView->setModel(model); 
 173.    QStringList headerList; 
 174.    headerList << "No." << "ID" << "Name" << "Age" << "Sex" << "Show"; 
 175.    model->setHorizontalHeaderLabels(headerList); 
 176.    tableView->verticalHeader()->setVisible(false); 
 177.    tableView->horizontalHeader()->setStretchLastSection(true); 
 178. 
 179.    //为每一列加载委托  
 180.    ReadOnlyDelegate readOnlyDelegate; 
 181.    tableView->setItemDelegateForColumn(0, &readOnlyDelegate); 
 182.    UserIDDelegate userIDDelegate; 
 183.    tableView->setItemDelegateForColumn(1, &userIDDelegate); 
 184.    AgeDelegate spinBoxDelegate; 
 185.    tableView->setItemDelegateForColumn(3, &spinBoxDelegate); 
 186.    SexDelegate comboBoxDelegate; 
 187.    tableView->setItemDelegateForColumn(4, &comboBoxDelegate); 
 188.    IconDelegate iconDelegate; 
 189.    tableView->setItemDelegateForColumn(5, &iconDelegate); 
 190. 
 191.    for(int i=0; i<10; i++) 
 192.    { 
 193.        QModelIndex index = model->index(i, 0, QModelIndex()); 
 194.        model->setData(index, i); 
 195.    } 
 196. 
 197.    tableView->show(); 
 198.    return app.exec(); 
 199.} 

本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2012-07/66820.htm

 

原创粉丝点击