Qt掃盲-QTableView理論總結

QTableView理論總結

  • 一、概述
  • 二、導航
  • 三、視覺外觀
  • 四、坐標系統
  • 五、示例代碼
    • 1. 性別代理
    • 2. 學生信息模型
    • 3. 對應視圖

一、概述

QTableView實現了一個tableview 來顯示model 中的元素。這個類用于提供之前由QTable類提供的標準表,但這個是使用Qt的model/view架構提供的更靈活的方法。

QTableView類是Model/View類之一,是Qt的Model/View框架的一部分。

QTableView實現了由QAbstractItemView類定義的接口,以允許它顯示由QAbstractItemModel類派生的 model 提供的數據。
在這里插入圖片描述
總的來說,model/view 的方式來查看修改數據更加的方便和容易的。

二、導航

我們可以通過鼠標點擊一個單元格,或者使用箭頭鍵來導航表格中的單元格。因為 QTableView 默認啟用tabKeyNavigation,我們還可以按Tab鍵和Backtab鍵在單元格之間移動。

三、視覺外觀

表格的垂直頭部可以通過函數verticalHeader()獲得,水平頭部可以通過函數horizontalHeader()獲得。可以使用rowHeight()來獲得表中每一行的高度。類似地,列的寬度可以使用columnWidth()得到。由于這兩個部件都是普通部件,因此可以使用它們的hide()函數隱藏它們。

可以使用hideRow()、hideColumn()、showRow()和showColumn()來隱藏和顯示行和列。可以使用selectRow()和selectColumn()來選擇列。表格會根據 showGrid 屬性顯示一個網格。就想我把這個設置為 false 之后。就沒有網格線啦。
在這里插入圖片描述

表視圖中顯示的項與其他項視圖中的項一樣,都使用標準委托進行渲染和編輯。

我們還可以用 代理的方式:用下列列表來選擇性別的方式
在這里插入圖片描述

然而,對于某些任務來說,能夠在表中插入其他控件有時是有用的。

用setIndexWidget()函數為特定的索引設置窗口組件,然后用indexWidget()檢索窗口組件。

默認情況下,表中的單元格不會擴展以填充可用空間。
您可以通過拉伸最后的標題部分來讓單元格填充可用空間。使用 horizontalHeader() 或 verticalHeader() 訪問相關的 headerview 標題對象,并設置標題的stretchLastSection屬性。

要根據每一列或每一行的空間需求來分配可用空間,可以調用視圖的resizeColumnsToContents()或resizeRowsToContents()函數。來實現出下面這種效果。

在這里插入圖片描述

四、坐標系統

對于某些特殊形式的表,能夠在行和列索引以及控件坐標之間進行轉換是很有用的。

rowAt()函數提供了指定行的視圖的y坐標;行索引可以通過rowViewportPosition()獲得對應的y坐標。

columnAt()和columnViewportPosition()函數提供了x坐標和列索引之間等價的轉換操作。

五、示例代碼

1. 性別代理

// SexComboxDelegate.h
#ifndef SEXCOMBOXDELEGATE_H
#define SEXCOMBOXDELEGATE_H#include <QObject>
#include <QStyledItemDelegate>
#include <QComboBox>class SexComboxDelegate : public QStyledItemDelegate
{Q_OBJECT
public:SexComboxDelegate(QObject *parent = nullptr);QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,const QModelIndex &index) const override;void setEditorData(QWidget *editor, const QModelIndex &index) const override;void setModelData(QWidget *editor, QAbstractItemModel *model,const QModelIndex &index) const override;void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,const QModelIndex &index) const override;
};#endif // SEXCOMBOXDELEGATE_H// SexComboxDelegate.cpp
#include "SexComboxDelegate.h"SexComboxDelegate::SexComboxDelegate(QObject *parent)
{}QWidget *SexComboxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{QComboBox *editor = new QComboBox(parent);editor->addItems(QStringList{"男", "女"});editor->setFrame(false);return editor;
}void SexComboxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{QComboBox *combox = static_cast<QComboBox*>(editor);combox->setCurrentIndex(combox->findText(index.model()->data(index, Qt::DisplayRole).toString()));
}void SexComboxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{QComboBox *combox = static_cast<QComboBox*>(editor);model->setData(index, combox->currentText(), Qt::EditRole);
}void SexComboxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{editor->setGeometry(option.rect);
}

2. 學生信息模型

// StudentModel.h
#ifndef STUDENTMODEL_H
#define STUDENTMODEL_H#include <QAbstractTableModel>
#include <QDebug>
#include <QColor>
#include <QBrush>
#include <QFont>class StudentModel: public QAbstractTableModel
{Q_OBJECT
public:StudentModel(QObject *parent = nullptr);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;QVariant headerData(int section, Qt::Orientation orientation, int role) const override;bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;Qt::ItemFlags flags(const QModelIndex &index) const override;void setRow(int newRow);void setColumn(int newColumn);void setTableHeader(QList<QString> *header);void setTableData(QList<QList<QString>> *data);signals:void editCompleted(const QString &);public slots:void SlotUpdateTable();
private:int row = 0;int column = 0;QList<QString> *m_header;QList<QList<QString>> *m_data;
};#endif // STUDENTMODEL_H// StudentModel.cpp
#include "StudentModel.h"StudentModel::StudentModel(QObject *parent) : QAbstractTableModel(parent)
{}int StudentModel::rowCount(const QModelIndex &parent) const
{return row;
}int StudentModel::columnCount(const QModelIndex &parent) const
{return column;
}QVariant StudentModel::data(const QModelIndex &index, int role) const
{if(role == Qt::DisplayRole || role == Qt::EditRole){return (*m_data)[index.row()][index.column()];}if(role == Qt::TextAlignmentRole){return Qt::AlignCenter;}if(role == Qt::BackgroundRole &&  index.row() % 2 == 0){return QBrush(QColor(50, 50, 50));}return QVariant();
}QVariant StudentModel::headerData(int section, Qt::Orientation orientation, int role) const
{if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {if(m_header->count() - 1 >= section)return m_header->at(section);}//qDebug()<<role << "--" << Qt::BackgroundRole;//    if(role == Qt::BackgroundRole)
//    {
//        return QBrush(QColor(156, 233, 248));
//    }
//    if(role == Qt::ForegroundRole)
//    {
//         return QBrush(QColor(156, 233, 248));
//    }if(role == Qt::FontRole){return QFont(tr("微軟雅黑"),10, QFont::DemiBold);}return QVariant();
}bool StudentModel::setData(const QModelIndex &index, const QVariant &value, int role)
{if (role == Qt::EditRole) {if (!checkIndex(index))return false;//save value from editor to member m_gridData(*m_data)[index.row()][index.column()] = value.toString();return true;}return false;
}Qt::ItemFlags StudentModel::flags(const QModelIndex &index) const
{return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
}void StudentModel::setRow(int newRow)
{row = newRow;
}void StudentModel::setColumn(int newColumn)
{column = newColumn;
}void StudentModel::setTableHeader(QList<QString> *header)
{m_header = header;
}void StudentModel::setTableData(QList<QList<QString> > *data)
{m_data = data;
}void StudentModel::SlotUpdateTable()
{emit dataChanged(createIndex(0, 0), createIndex(row, column), {Qt::DisplayRole});
}

3. 對應視圖

// StudentWD.h
#ifndef STUDENTWD_H
#define STUDENTWD_H#include <QWidget>
#include <Model/StudentModel.h>
#include <QFileDialog>
#include <QStandardPaths>
#include <QFile>
#include <QTextStream>
#include <Delegate/SpinBoxDelegate.h>
#include <Delegate/SexComboxDelegate.h>namespace Ui {
class StudentWD;
}class StudentWD : public QWidget
{Q_OBJECTpublic:explicit StudentWD(QWidget *parent = nullptr);~StudentWD();private slots:void on_ImportBtn_clicked();private:Ui::StudentWD *ui;StudentModel *model;SpinBoxDelegate *spinBoxDelegate;SexComboxDelegate *sexBoxDeleage;QList<QList<QString>> subject_table;QList<QString> subject_title;
};#endif // STUDENTWD_H
// StudentWD.cpp
#include "StudentWD.h"
#include "ui_StudentWD.h"StudentWD::StudentWD(QWidget *parent) :QWidget(parent),ui(new Ui::StudentWD),model(new StudentModel),spinBoxDelegate(new SpinBoxDelegate),sexBoxDeleage(new SexComboxDelegate)
{ui->setupUi(this);ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);}StudentWD::~StudentWD()
{delete ui;
}void StudentWD::on_ImportBtn_clicked()
{QString fileName = QFileDialog::getOpenFileName(this,tr("打開 csv 文件"), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation), tr("Txt Files (*.txt *.csv *.*)"));subject_table.clear();subject_title.clear();if(!fileName.isNull() && !fileName.isEmpty()){QFile file(fileName);if (!file.open(QIODevice::ReadOnly | QIODevice::Text))return;int i = 0;QTextStream in(&file);in.setCodec("UTF-8");while (!file.atEnd()) {QString line = file.readLine();if(i == 0){subject_title = line.split(",", QString::SkipEmptyParts);subject_title.last() = subject_title.last().trimmed();i++;continue;}subject_table.append(line.split(",", QString::SkipEmptyParts));subject_table.last().last() = subject_table.last().last().trimmed();}ui->Total_Subject_SB->setValue(subject_title.count());ui->Total_People_SB->setValue(subject_table.count());model->setColumn(subject_title.count());model->setRow(subject_table.count());model->setTableData(& subject_table);model->setTableHeader(& subject_title);ui->tableView->setModel(model);ui->tableView->setItemDelegateForColumn(0, spinBoxDelegate);ui->tableView->setShowGrid(true);ui->tableView->setItemDelegateForColumn(1, sexBoxDeleage);for (int i = 2; i < subject_table.count(); ++i) {ui->tableView->setItemDelegateForColumn(i, spinBoxDelegate);}ui->tableView->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);}}

對應的ui文件
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/43085.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/43085.shtml
英文地址,請注明出處:http://en.pswp.cn/news/43085.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

MySQL 存儲過程

create procedure 存儲過程名 &#xff08;in | out | INPUT 參數名 參數類型&#xff0c;。。。&#xff09; 【characteristics 。。。】begin存儲過程體end存儲過程的參數類型 IN 、OUT、INPUT 都可以在一個存儲過程帶多個 沒有參數&#xff08;無參數無返回&#xff09;僅…

ProGuard + SpringBoot3 + JDK17

1、pom依賴 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apache.org/POM/4.…

android平臺的語音聊天助手源碼

目錄 1 android平臺的語音聊天助手源碼 1.1 Setting 1.1.1 onChildClick 1.1.2 if (groupPosition == 0) {// 語音識別設置 android平臺的語音聊天助手源碼 Setting onChildClick

神經網絡基礎-神經網絡補充概念-11-向量化邏輯回歸

概念 通過使用 NumPy 數組來進行矩陣運算&#xff0c;將循環操作向量化。 向量化的好處在于它可以同時處理多個樣本&#xff0c;從而加速計算過程。在實際應用中&#xff0c;尤其是處理大規模數據集時&#xff0c;向量化可以顯著提高代碼的效率。 代碼實現-以邏輯回歸為例 i…

邊緣網絡的作用及管理工具

自從引入軟件即服務 &#xff08;SaaS&#xff09; 以來&#xff0c;它一直引領著全球按需軟件部署創新的競賽&#xff0c;它提供的靈活性以及其云計算架構帶來的易于集成使其成為交付業務應用程序的標準。 在 SaaS 模型中&#xff0c;最佳用戶體驗的三重奏涉及無縫設置、低延…

JMeter 特殊組件-邏輯控制器與BeanShell PreProcessor 使用示例

文章目錄 前言JMeter 特殊組件-邏輯控制器與BeanShell PreProcessor 使用示例1. 邏輯控制器使用1.1. While Controller 使用示例1.2. 如果&#xff08;If&#xff09;控制器 使用示例 2. BeanShell PreProcessor 使用示例 前言 如果您覺得有用的話&#xff0c;記得給博主點個贊…

Java課題筆記~ SpringBoot簡介

1. 入門案例 問題導入 SpringMVC的HelloWord程序大家還記得嗎&#xff1f; SpringBoot是由Pivotal團隊提供的全新框架&#xff0c;其設計目的是用來簡化Spring應用的初始搭建以及開發過程 原生開發SpringMVC程序過程 1.1 入門案例開發步驟 ①&#xff1a;創建新模塊&#…

設計模式-過濾器模式(使用案例)

過濾器模式&#xff08;Filter Pattern&#xff09;或標準模式&#xff08;Criteria Pattern&#xff09;是一種設計模式&#xff0c;這種模式允許開發人員使用不同的標準來過濾一組對象&#xff0c;通過邏輯運算以解耦的方式把它們連接起來。這種類型的設計模式屬于結構型模式…

服務器安裝centos7踩坑

1、制作啟動工具 下載iso https://developer.aliyun.com/mirror/?spma2c6h.25603864.0.0.20387abbo2RFbn http://mirrors.aliyun.com/centos/7.9.2009/isos/x86_64/?spma2c6h.25603864.0.0.1995f5ad4AhJaW下載 UltraISO https://cn.ultraiso.net/插入u盤啟動 到了如圖所示頁面…

nginx php-fpm安裝配置

nginx php-fpm安裝配置 nginx本身不能處理PHP&#xff0c;它只是個web服務器&#xff0c;當接收到請求后&#xff0c;如果是php請求&#xff0c;則發給php解釋器處理&#xff0c;并把結果返回給客戶端。 nginx一般是把請求發fastcgi管理進程處理&#xff0c;fascgi管理進程選…

架構演進及常用架構

1架構演進及常用架構 1.1單體分層架構 1.2 多應用微服務架構 1.3 分布式集群部署 部署 CDN 節點&#xff1a; 用戶訪問量的增加意味著用戶地域的分散請求&#xff0c;如果所有請求都直接發送中心服務器的話&#xff0c;距離越遠&#xff0c;響應速度越差&#xff0c;這時就需…

【編織時空四:探究順序表與鏈表的數據之旅】

本章重點 鏈表的分類 帶頭雙向循環鏈表接口實現 順序表和鏈表的區別 緩存利用率參考存儲體系結構 以及 局部原理性。 一、鏈表的分類 實際中鏈表的結構非常多樣&#xff0c;以下情況組合起來就有8種鏈表結構&#xff1a; 1. 單向或者雙向 2. 帶頭或者不帶頭 3. 循環或者非…

yolov5封裝進ros系統

一&#xff0c;要具備ROS環境 ROS環境搭建可以參考我之前的文章 ROS參考文章1 ROS參考文章2 ? 建立ROS工作空間 ROS系統由自己的編譯空間規則。 cd 你自己想要的文件夾&#xff08;我一般是home目錄&#xff09; mkdir -p (你自己的文件夾名字&#xff0c;比如我是yolov5…

C++的stack和queue+優先隊列

文章目錄 什么是容器適配器底層邏輯為什么選擇deque作為stack和queue的底層默認容器優先隊列優先隊列的模擬實現stack和queue的模擬實現 什么是容器適配器 適配器是一種設計模式(設計模式是一套被反復使用的、多數人知曉的、經過分類編目的、代碼設計經驗的總 結)&#xff0c;…

Greenplum多級分區表添加分區報錯ERROR: no partitions specified at depth 2

一般來說&#xff0c;我們二級分區表都會使用模版&#xff0c;如果沒有使用模版特性&#xff0c;那么就會報ERROR: no partitions specified at depth 2類似的錯誤。因為沒有模版&#xff0c;必須要顯式指定分區。 當然我們在建表的時候&#xff0c;如果沒有指定&#xff0c;那…

PyTorch訓練深度卷積生成對抗網絡DCGAN

文章目錄 DCGAN介紹代碼結果參考 DCGAN介紹 將CNN和GAN結合起來&#xff0c;把監督學習和無監督學習結合起來。具體解釋可以參見 深度卷積對抗生成網絡(DCGAN) DCGAN的生成器結構&#xff1a; 圖片來源&#xff1a;https://arxiv.org/abs/1511.06434 代碼 model.py impor…

VSCode 使用總結

快捷鍵 在 Visual Studio Code (VSCode) 中&#xff0c;有許多常用的快捷鍵可以提高編程效率。以下是一些常見的 VSCode 編程項目快捷鍵&#xff1a; 編輯器操作&#xff1a; 撤銷&#xff1a;Ctrl Z重做&#xff1a;Ctrl Shift Z復制&#xff1a;Ctrl C剪切&#xff1a;C…

Electron入門,項目啟動。

electron 簡單介紹&#xff1a; 實現&#xff1a;HTML/CSS/JS桌面程序&#xff0c;搭建跨平臺桌面應用。 electron 官方文檔&#xff1a; [https://electronjs.org/docs] 本文是基于以下2篇文章且自行實踐過的&#xff0c;可行性真實有效。 文章1&#xff1a; https://www.cnbl…

題解 | #1005.List Reshape# 2023杭電暑期多校9

1005.List Reshape 簽到題 題目大意 按一定格式給定一個純數字一維數組&#xff0c;按給定格式輸出成二維數組。 解題思路 讀入初始數組字符串&#xff0c;將每個數字分離&#xff0c;按要求輸出即可 參考代碼 參考代碼為已AC代碼主干&#xff0c;其中部分功能需讀者自行…

學習Vue:組件通信

組件化開發在現代前端開發中是一種關鍵的方法&#xff0c;它能夠將復雜的應用程序拆分為更小、更可管理的獨立組件。在Vue.js中&#xff0c;父子組件通信是組件化開發中的重要概念&#xff0c;同時我們還會討論其他組件間通信的方式。 父子組件通信&#xff1a;Props 和 Events…