当前位置:网站首页>QML combines qsqltablemodel to dynamically load data MVC "recommended collection"
QML combines qsqltablemodel to dynamically load data MVC "recommended collection"
2022-07-25 20:01:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
Results the preview :
One 、 Prepare the corresponding QSqlTableModel
#ifndef LOCALMUSICMODEL_H
#define LOCALMUSICMODEL_H
#include <QObject>
#include <QSqlTableModel>
#include <QMediaPlayer>
#include "libzplay.h"
using namespace libZPlay;
struct songInfo
{
QString Artist;
QString title;
QString album;
qint32 duration = 0;
QString path;
};
class LocalMusicModel : public QSqlTableModel
{
Q_OBJECT
Q_PROPERTY(int m_musicNum READ musicNum WRITE setMusicNum NOTIFY musicNumChanged)
public:
explicit LocalMusicModel(QObject *parent = nullptr);
QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE;
Q_INVOKABLE void reloadMusicRecord(const QString &path);
int musicNum(){return m_musicNum;}
void setMusicNum(int val){
m_musicNum = val;
emit musicNumChanged();
}
signals:
void musicNumChanged();
private:
void parseMusicInfo(QString path);
void clearDb();
private:
ZPlay *player;
int m_musicNum = 0;
};
#endif // LOCALMUSICMODEL_H#include "localmusicmodel.h"
#include <QDateTime>
#include <QSqlRecord>
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>
#include <QDir>
static const char *localMusicTableName = "LocalMusicInfo";
static void createTable()
{
if (QSqlDatabase::database().tables().contains(localMusicTableName)) {
// The table already exists; we don't need to do anything.
return;
}
QSqlQuery query;
QString sql_ = QStringLiteral("CREATE TABLE IF NOT EXISTS [LocalMusicInfo] ( \
[title] VARCHAR2 , \
[singer] VARCHAR2 , \
[album] VARCHAR2 , \
[duration] INTEGER ,\
[path] VARCHAR2 NOT NULL , \
UNIQUE([path]) ON CONFLICT REPLACE \
)");
if (!query.exec(sql_)) {
qFatal("Failed to query database: %s", qPrintable(query.lastError().text()));
}
//query.exec("INSERT INTO LocalMusicInfo VALUES('title', 'singer', 'album', 123,'c://')");
}
LocalMusicModel::LocalMusicModel(QObject *parent)
: QSqlTableModel(parent)
{
createTable();
setTable(localMusicTableName);
/* You can see that this model is very powerful , And completely separated from SQL sentence , Even if you don't know much about databases ,
* You can also use it for most common operations . This model provides a buffer , You can save all changes to model in ,
* Only when we execute the commit modification , Will actually write to the database . Of course, it's also because we set its saving policy at the beginning :
submitAll(); revertAll();*/
setEditStrategy(QSqlTableModel::OnManualSubmit);
select();
player = CreateZPlay();
setMusicNum(this->rowCount());
}
QVariant LocalMusicModel::data(const QModelIndex &index, int role) const
{
if (role < Qt::UserRole)
return QSqlTableModel::data(index, role);
const QSqlRecord sqlRecord = record(index.row());
//qDebug() << sqlRecord.value(role - Qt::UserRole);
switch (role) {
case Qt::UserRole:
if(sqlRecord.value(0).toString().isEmpty())
{
QString path = sqlRecord.value(role - Qt::UserRole + 4).toString();
path = path.right(path.lastIndexOf('/'));
path.chop(4);
return path.simplified();
}
break;
case Qt::UserRole+1:
if(sqlRecord.value(1).toString().isEmpty())
return tr(" Unknown singer ");
break;
case Qt::UserRole+2:
if(sqlRecord.value(2).toString().isEmpty())
return tr(" Unknown album ");
break;
case Qt::UserRole+3:
int time = sqlRecord.value(3).toInt();
return QString("%1:%2").arg(time/60).arg(time%60,2,10,QChar('0'));
}
return sqlRecord.value(role - Qt::UserRole);
}
QHash<int, QByteArray> LocalMusicModel::roleNames() const
{
QHash<int, QByteArray> names;
names[Qt::UserRole] = "title";
names[Qt::UserRole + 1] = "singer";
names[Qt::UserRole + 2] = "album";
names[Qt::UserRole + 3] = "duration";
names[Qt::UserRole + 4] = "path";
return names;
}
void LocalMusicModel::reloadMusicRecord(const QString &path_)
{
parseMusicInfo(path_);
}
// Get the information of all songs in the specified directory
void LocalMusicModel::parseMusicInfo(QString path)
{
QList<songInfo> songRecords;
QStringList dirList=path.split(",");
QString temp;
foreach (temp, dirList) {
temp=temp.right(temp.length()-8);
QDir dir(temp);
dir.setNameFilters(QStringList() << "*.mp3" << "*.flac" << "*.wav");
QFileInfoList fileList=dir.entryInfoList();
QFileInfo fileInfo;
foreach (fileInfo, fileList) {
TID3InfoEx id3_info;
// If used directly LoadFileID3Ex function , There will be no long message
if(player->OpenFile((const char*) fileInfo.absoluteFilePath().toLocal8Bit(),sfAutodetect))
if(player->LoadID3Ex(&id3_info,1))
{
songInfo tempSongInfo;
tempSongInfo.title = QString::fromLocal8Bit(id3_info.Title); // Music title
tempSongInfo.Artist = QString::fromLocal8Bit(id3_info.Artist); // singer
tempSongInfo.path = fileInfo.absoluteFilePath(); // route
tempSongInfo.album = QString::fromLocal8Bit(id3_info.Album); // Album
// get stream info, Get duration information
TStreamInfo pInfo;
player->GetStreamInfo(&pInfo);
tempSongInfo.duration =pInfo.Length.sec;
songRecords.append(tempSongInfo);
}
else
{
qDebug() << QString("No ID3 data:%1\r\n\r\n").arg(QString::fromLocal8Bit(player->GetError()));
}
else
{
qDebug() << "LoadID3Ex faild";
}
}
}
clearDb();
QSqlRecord newRecord = record();
for(auto songItem : songRecords)
{
newRecord.setValue("title", songItem.title);
newRecord.setValue("singer", songItem.Artist);
newRecord.setValue("album", songItem.album);
newRecord.setValue("duration", songItem.duration);
newRecord.setValue("path", songItem.path);
if (!insertRecord(rowCount(), newRecord)) {
qWarning() << "Failed to send message:" << lastError().text();
return;
}
}
submitAll();// Submit database
setMusicNum(songRecords.size());
}
void LocalMusicModel::clearDb()
{
if (!QSqlDatabase::database().tables().contains(localMusicTableName)) {
createTable();
}
QSqlQuery query;
QString sql_ = QStringLiteral("delete from [LocalMusicInfo]");
if (!query.exec(sql_)) {
qFatal("Failed to query database: %s", qPrintable(query.lastError().text()));
}
qDebug() << "clear table ok";
}The key is
QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE;QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;Give you what you need data Set it up role, convenient qml To call .
Two 、qml call
main.cpp
qmlRegisterType<LocalMusicModel>("io.qt.CloudMusic", 1, 0, "LocalMusicModel");qml:
import io.qt.CloudMusic 1.0LocalMusicModel{
id:localmusic;} TableView{
id: tableview
anchors.fill: parent
visible: localmusic.m_musicNum >0
backgroundVisible: false;
frameVisible: false;
//itemDelegate: StandardTabelItemDelegate{} // agent
//headerDelegate: headerDele; // Header delegation
//rowDelegate: rowDele; // Bank entrustment
model: localmusic
TableViewColumn {
role: "title"
title: qsTr(" title ")
width: 300
}
TableViewColumn {
role: "singer"
title: qsTr(" singer ")
width: 300
}
TableViewColumn {
role: "album"
title: qsTr(" Album ")
width: 300
}
TableViewColumn {
role: "duration"
title: qsTr(" Duration ")
width: 300
}
}The agency will be further improved later
qml To write Netease cloud music catalog from scratch
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/127739.html Link to the original text :https://javaforall.cn
边栏推荐
- 导电滑环在机械设备方面的应用
- Detailed explanation of three methods of selenium setting element waiting
- How to get started quickly in software testing
- CarSim仿真快速入门(十四)—CarSim-Simulink联合仿真
- 手机端触摸图片slider轮播插件photoswipe.js
- Prescan quick start to master Lesson 19: prescan actuator configuration, track synchronization and non configuration of multiple tracks
- PyTorch 模型 onnx 文件的导出和调用
- C language learning diary 3 - realloc function
- 各厂商网络虚拟化的优势
- High number_ Chapter 3 learning experience and summary of multiple integral
猜你喜欢

C # add multi line and multi column text watermark in word

wallys//IPQ5018/IPQ6010/PD-60 802.3AT Input Output 10/100/1000M

Advantages of network virtualization of various manufacturers

【神器】截图+贴图工具 Snipaste

How does tiktok break zero?

Connecting to the database warning establishing SSL connection without server's identity verification is not recommended

03 isomorphism of tree 1
![[wp]ctfshow-web introductory information collection](/img/22/c2e5cca918800dda9df27272eb9871.png)
[wp]ctfshow-web introductory information collection
EZDML reverse engineering import database analysis practical operation tutorial

Mutual conversion of camera internal parameter matrix K and FOV
随机推荐
Binarysearch basic binary search
C merge set
How to ensure the quality of customized slip rings
一元函数积分学_分部积分法
4、Nacos 配置中心源码解析之 服务端启动
Google pixel 6A off screen fingerprint scanner has major security vulnerabilities
IP地址的概念
[wp]ctfshow-web入门信息搜集
Three skills of interface request merging, and the performance is directly exploded!
qml 结合 QSqlTableModel 动态加载数据 MVC「建议收藏」
PreScan快速入门到精通第十八讲之PreScan轨迹编辑的特殊功能
飞行器pid控制(旋翼飞控)
On interface encryption
[artifact] screenshot + mapping tool snipaste
Amrita Institute of Engineering | reinforcement active learning method for optimizing sampling in terms extraction of emotional analysis
Oracle数据库下载、安装、使用教程及问题汇总
9. < tag dynamic programming and subsequence, subarray> lt.718. Longest repeated subarray + lt.1143. Longest common subsequence
Bash does not add single quotes to your string
Log in to Baidu online disk with cookies (websites use cookies)
wallys//IPQ5018/IPQ6010/PD-60 802.3AT Input Output 10/100/1000M