(四)Qt實現自定義模型基于QAbstractTableModel (一般)

Qt實現自定義模型基于QAbstractTableModel

兩個例子

例子1代碼

Main.cpp

#include <QtGui>#include "currencymodel.h"int main(int argc, char *argv[])
{QApplication app(argc, argv);//數據源QMap<QString, double> currencyMap;currencyMap.insert("AUD", 1.3259);currencyMap.insert("CHF", 1.2970);currencyMap.insert("CZK", 24.510);currencyMap.insert("DKK", 6.2168);currencyMap.insert("EUR", 0.8333);currencyMap.insert("GBP", 0.5661);currencyMap.insert("HKD", 7.7562);currencyMap.insert("JPY", 112.92);currencyMap.insert("NOK", 6.5200);currencyMap.insert("NZD", 1.4697);currencyMap.insert("SEK", 7.8180);currencyMap.insert("SGD", 1.6901);currencyMap.insert("USD", 1.0000);//自定義表模型
    CurrencyModel currencyModel;currencyModel.setCurrencyMap(currencyMap);//表視圖
    QTableView tableView;//設置視圖模型tableView.setModel(&currencyModel);//設置交替顏色tableView.setAlternatingRowColors(true);tableView.setWindowTitle(QObject::tr("Currencies"));tableView.show();return app.exec();
}

currencymodel.h

#ifndef CURRENCYMODEL_H
#define CURRENCYMODEL_H#include <QAbstractTableModel>
#include <QMap>class CurrencyModel : public QAbstractTableModel
{
public:CurrencyModel(QObject *parent = 0);void setCurrencyMap(const QMap<QString, double> &map);int rowCount(const QModelIndex &parent) const;int columnCount(const QModelIndex &parent) const;QVariant data(const QModelIndex &index, int role) const;QVariant headerData(int section, Qt::Orientation orientation,int role) const;private:QString currencyAt(int offset) const;QMap<QString, double> currencyMap;
};#endif

currencymodel.cpp

#include <QtCore>#include "currencymodel.h"CurrencyModel::CurrencyModel(QObject *parent): QAbstractTableModel(parent)
{
}void CurrencyModel::setCurrencyMap(const QMap<QString, double> &map)
{currencyMap = map;//重置模型至原始狀態,告訴所有視圖,他們數據都無效,強制刷新數據
    reset();
}//返回行數
int CurrencyModel::rowCount(const QModelIndex & /* parent */) const
{return currencyMap.count();
}
//返回列數
int CurrencyModel::columnCount(const QModelIndex & /* parent */) const
{return currencyMap.count();
}//返回一個項的任意角色的值,這個項被指定為QModelIndex
QVariant CurrencyModel::data(const QModelIndex &index, int role) const
{if (!index.isValid())return QVariant();if (role == Qt::TextAlignmentRole) {return int(Qt::AlignRight | Qt::AlignVCenter);} else if (role == Qt::DisplayRole) {QString rowCurrency = currencyAt(index.row());QString columnCurrency = currencyAt(index.column());if (currencyMap.value(rowCurrency) == 0.0)return "####";double amount = currencyMap.value(columnCurrency)/ currencyMap.value(rowCurrency);return QString("%1").arg(amount, 0, 'f', 4);}return QVariant();
}
//返回表頭名稱,(行號或列號,水平或垂直,角色)
QVariant CurrencyModel::headerData(int section,Qt::Orientation /* orientation */,int role) const
{if (role != Qt::DisplayRole)return QVariant();return currencyAt(section);
}
//獲取當前關鍵字
QString CurrencyModel::currencyAt(int offset) const
{return (currencyMap.begin() + offset).key();
}

例子2代碼

Main.cpp

#include <QApplication>
#include <QHeaderView>
#include <QTableView>#include "citymodel.h"int main(int argc, char *argv[])
{QApplication app(argc, argv);//保存城市名
    QStringList cities;cities << "Arvika" << "Boden" << "Eskilstuna" << "Falun"<< "Filipstad" << "Halmstad" << "Helsingborg" << "Karlstad"<< "Kiruna" << "Kramfors" << "Motala" << "Sandviken"<< "Skara" << "Stockholm" << "Sundsvall" << "Trelleborg";//模型
    CityModel cityModel;//
    cityModel.setCities(cities);QTableView tableView;tableView.setModel(&cityModel);tableView.setAlternatingRowColors(true);tableView.setWindowTitle(QObject::tr("Cities"));tableView.show();return app.exec();
}

citymodel.h

#ifndef CITYMODEL_H
#define CITYMODEL_H#include <QAbstractTableModel>
#include <QStringList>
#include <QVector>class CityModel : public QAbstractTableModel
{Q_OBJECTpublic:CityModel(QObject *parent = 0);void setCities(const QStringList &cityNames);int rowCount(const QModelIndex &parent) const;int columnCount(const QModelIndex &parent) const;QVariant data(const QModelIndex &index, int role) const;bool setData(const QModelIndex &index, const QVariant &value,int role);QVariant headerData(int section, Qt::Orientation orientation,int role) const;Qt::ItemFlags flags(const QModelIndex &index) const;private:int offsetOf(int row, int column) const;QStringList cities;QVector<int> distances;
};#endif

citymodel.cpp

#include <QtCore>#include "citymodel.h"CityModel::CityModel(QObject *parent): QAbstractTableModel(parent)
{
}
//設定一下數據源
void CityModel::setCities(const QStringList &cityNames)
{cities = cityNames;//重新設置一下QVector distances的矩陣大小的,中間對角線為0不用存distances.resize(cities.count() * (cities.count() - 1) / 2);//填充所有距離值為0distances.fill(0);//刷新所有視圖數據
    reset();
}
//模型行數
int CityModel::rowCount(const QModelIndex & /* parent */) const
{return cities.count();
}
//模型列數
int CityModel::columnCount(const QModelIndex & /* parent */) const
{return cities.count();
}
//賦值模型每個項的數據
QVariant CityModel::data(const QModelIndex &index, int role) const
{if (!index.isValid())return QVariant();if (role == Qt::TextAlignmentRole) {return int(Qt::AlignRight | Qt::AlignVCenter);} else if (role == Qt::DisplayRole) {if (index.row() == index.column())return 0;int offset = offsetOf(index.row(), index.column());return distances[offset];}return QVariant();
}
//編輯一個項
bool CityModel::setData(const QModelIndex &index,const QVariant &value, int role)
{if (index.isValid() && index.row() != index.column()&& role == Qt::EditRole) {int offset = offsetOf(index.row(), index.column());distances[offset] = value.toInt();//交換對應項的模型索引QModelIndex transposedIndex = createIndex(index.column(),index.row());//某項發生改變,發射信號( between topLeft and bottomRight inclusive)
        emit dataChanged(index, index);emit dataChanged(transposedIndex, transposedIndex);return true;}return false;
}//返回列表頭
QVariant CityModel::headerData(int section,Qt::Orientation /* orientation */,int role) const
{//返回在Cities字符串列表中給定偏移量的城市名稱if (role == Qt::DisplayRole)return cities[section];return QVariant();
}
//返回對一個項相關的操作的標識符(例如,是否可以編輯或者是否已選中等)
Qt::ItemFlags CityModel::flags(const QModelIndex &index) const
{Qt::ItemFlags flags = QAbstractItemModel::flags(index);if (index.row() != index.column())flags |= Qt::ItemIsEditable;return flags;
}
//計算偏移量
int CityModel::offsetOf(int row, int column) const
{if (row < column)qSwap(row, column);return (row * (row - 1) / 2) + column;
}

轉自:http://qimo601.iteye.com/blog/1534331

轉載于:https://www.cnblogs.com/liushui-sky/p/5775579.html

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

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

相關文章

pt-query-digest使用介紹【轉】

本文來自&#xff1a;http://isadba.com/?p651 一、pt-query-digest參數介紹. pt-query-digest --useranemometer --passwordanemometerpass --review h192.168.11.28,Dslow_query_log,tglobal_query_review \--history h192.168.11.28,Dslow_query_log,tglobal_query_re…

python代碼模板_python 代碼模板

python中的Module是比較重要的概念。常見的情況是&#xff0c;事先寫好一個.py文 件&#xff0c;在另一個文件中需要import時&#xff0c;將事先寫好的.py文件拷貝 到當前目錄&#xff0c;或者是在sys.path中增加事先寫好的.py文件所在的目錄&#xff0c;然后import。這樣的做法…

Java并發教程–重入鎖

Java的synced關鍵字是一個很棒的工具–它使我們能夠以一種簡單可靠的方式來同步對關鍵部分的訪問&#xff0c;而且也不難理解。 但是有時我們需要對同步進行更多控制。 我們要么需要分別控制訪問類型&#xff08;讀取和寫入&#xff09;&#xff0c;要么使用起來很麻煩&#xf…

找出互聯網類似以下圖的實例

轉載于:https://www.cnblogs.com/sghcjy/p/4978851.html

python比較運算符重載_python運算符重載

1、打印操作會首先嘗試__str__和str內置函數&#xff0c;他通常返回一個用戶友好顯示。__repr__用于所有其他環境&#xff0c;用于交互式模式下提示回應以及repr函數&#xff0c;如果沒有使用__str__&#xff0c;則會使用print和str。它通常返回一個編碼字符串&#xff0c;可以…

使用Spring MVC開發Restful Web服務

REST簡介 摘自Wikipedia&#xff1a; REST風格的體系結構由客戶端和服務器組成。 客戶端向服務器發起請求&#xff1b; 服務器處理請求并返回適當的響應。 請求和響應圍繞資源表示的傳遞而構建。 資源本質上可以是可以解決的任何連貫且有意義的概念。 正如您所閱讀的&#xff0…

深入Java核心 Java內存分配原理精講

深入Java核心 Java內存分配原理精講 Java內存分配與管理是Java的核心技術之一&#xff0c;之前我們曾介紹過Java的內存管理與內存泄露以及Java垃圾回收方面的知識&#xff0c;今天我們再次深入Java核心&#xff0c;詳細介紹一下Java在內存分配方面的知識。一般Java在內存分配時…

iOS正則表達式(親測,持續更新)

先來說說判斷方法,書寫不簡介但是好理解: -(BOOL)isRealNmaeString:(NSString *)str{NSString *pattern "填寫正則表達式";NSPredicate *pred [NSPredicate predicateWithFormat:"SELF MATCHES %", pattern];BOOL isMatch [pred evaluateWithObject:str…

python新建一個文件夾需要重新安裝模塊嗎_解決pycharm每次新建項目都要重新安裝一些第三方庫的問題...

目前有三個解決辦法&#xff0c;也是親測有用的&#xff1a;第一個方法&#xff1a;因為之前有通過pycharm的project interpreter里的號添加過一些庫&#xff0c;但添加的庫只是指定的項目用的&#xff0c;如果想要用&#xff0c;就必須用之前的項目的python解釋器&#xff0c;…

端到端測試的濫用–測試技術2

我的上一個博客是有關測試代碼方法的一系列博客中的第一篇&#xff0c;概述了使用一種非常常見的模式從數據庫檢索地址的簡單方案&#xff1a; …并描述了一種非常通用的測試技術&#xff1a; 不編寫測試 &#xff0c; 而是手動進行所有操作。 今天的博客涵蓋了另一種實踐&…

[AlwaysOn Availability Groups]排查:AG超過RPO

[AlwaysOn Availability Groups]排查&#xff1a;AG超過RPO 排查&#xff1a;AG超過RPO 在異步提交的secondary上執行了切換&#xff0c;你可能會發現數據的丟失大于RPO&#xff0c;或者在計算可以忍受的數據都是超過了RPO。 1.通常原因 1.網絡延遲太高&#xff0c;網絡吞吐量太…

那些年困擾我們的Linux 的蠕蟲、病毒和木馬

雖然針對Linux的惡意軟件并不像針對Windows乃至OS X那樣普遍&#xff0c;但是近些年來&#xff0c;Linux面臨的安全威脅卻變得越來越多、越來越嚴重。個中原因包括&#xff0c;手機爆炸性的普及意味著基于Linux的安卓成為惡意黑 客最具吸引力的目標之一&#xff0c;以及使用Lin…

python單元測試框架unittest介紹和使用_Python+Selenium框架設計篇之-簡單介紹unittest單元測試框架...

前面文章已經簡單介紹了一些關于自動化測試框架的介紹&#xff0c;知道了什么是自動化測試框架&#xff0c;主要有哪些特點&#xff0c;基本組成部分等。在繼續介紹框架設計之前&#xff0c;我們先來學習一個工具&#xff0c;叫unittest。unittest是一個單元測試框架&#xff0…

使用PowerMock模擬靜態方法

在最近的博客中&#xff0c;我試圖強調使用依賴注入的好處&#xff0c;并表達一種想法&#xff0c;即這種技術的主要好處之一是&#xff0c;通過在類之間提供高度的隔離&#xff0c;它可以使您更輕松地測試代碼&#xff0c;并且得出的結論是&#xff0c;許多好的測試等于好的代…

多態之向上轉型

//向上轉型&#xff0c;子類引用指向父類對象 public class UpcastingDemo{ public static void main(String[] args){ Employee enew Employee(); System.out.println(e.grade); e.job(); e.run(); System.out.println("\n"); Manager mnew Manager(…

(轉)FPGA異步時序和多時鐘模塊

http://bbs.ednchina.com/BLOG_ARTICLE_3019907.HTM 第六章 時鐘域 有一個有趣的現象&#xff0c;眾多數字設計特別是與FPGA設計相關的教科書都特別強調整個設計最好采用唯一的時鐘域。換句話說&#xff0c;只有一個獨立的網絡可以驅動一個設計中所有觸發器的時鐘端口。雖然…

穆里尼奧:與范加爾風格不同,轉變需要時間

據英媒報道&#xff0c;曼聯主帥穆里尼奧近日向媒體表示自己很難繼續遵循前任主帥范加爾的理念去建立球隊&#xff0c;因為他們兩人有著完全不同的想法。 穆里尼奧近日在接受BT Sport的采訪時表示&#xff1a;“這份工作對于我來說最難的地方便是我與范加爾是非常不同的教練&am…

怎么檢測不到我的音頻_Linux 上的最佳音頻編輯工具推薦 | Linux 中國

在 Linux 上&#xff0c;有很多種音頻編輯器可供你選用。不論你是一個專業的音樂制作人&#xff0c;還是只想學學怎么做出超棒的音樂的愛好者&#xff0c;這些強大的音頻編輯器都是很有用的工具。-- Ankush Das(作者)在 Linux 上&#xff0c;有很多種音頻編輯器可供你選用。不論…

具有GlassFish和一致性的高性能JPA –第3部分

在我的四部分系列的第三部分中&#xff0c;我將解釋將Coherence與EclipseLink和GlassFish結合使用的第二種策略。 這就是通過EclipseLink使用Coherence作為二級緩存&#xff08;L2&#xff09;的全部內容。 一般的做法 這種方法將Coherence數據網格應用于依賴于無法完全預加載到…

接口使用時注意

interface Service{ void doSome(); //方法的默認修飾符為public abstract } public class InterfaceNote implements Service{ //方法默認的修飾符為 default void doSome(){ System.out.println("做一些服務&#xff01;"); } public static void main(String…