QT-Mysql数据库图形化接口

QT += sql

mysqloper.h

qsqlrelationaltablemodelview.h

/*************************************************************************
接口描述:Mysql数据库图形化接口
拟制:
接口版本:V1.0
时间:20230727
说明:支持是否创建界面类QTableView,默认QTableView不允许增删改查功能,支持创建外键表
*************************************************************************/
#ifndef QSQLRELATIONALTABLEMODELVIEW_H
#define QSQLRELATIONALTABLEMODELVIEW_H

#include <qsqlrelationaltablemodel.h>
#include <qsqlrelationaldelegate.h>
#include <QTableView>
#include <QMenu>
#include <QHeaderView>
#include <QMessageBox>
#include "mysqloper.h"//源码在其他博文中
#include <QDateTimeEdit>
#include <QStyledItemDelegate>

class QDateTimeItemDelegate : public QStyledItemDelegate
{
    Q_OBJECT

public:
    explicit QDateTimeItemDelegate(QString qsDataFormat = "yyyy/MM/dd HH:mm:ss", QObject *parent = nullptr)
        : QStyledItemDelegate(parent)
    {
        m_qsDataFormat = qsDataFormat;
    };

private:
    QString m_qsDataFormat;

    // QStyledItemDelegate interface
public:
    virtual QString displayText(const QVariant &value, const QLocale &locale) const override
    {
        if(value.type() == QVariant::DateTime)
        {
            return value.toDateTime().toString(m_qsDataFormat);
        }
        return QStyledItemDelegate::displayText(value, locale);
    };

    virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        const QSqlRelationalTableModel *sqlModel = qobject_cast<const QSqlRelationalTableModel *>(index.model());
        QVariant variant = sqlModel->data(index, Qt::DisplayRole);
        if(variant.type() == QVariant::DateTime)
        {
            QDateTimeEdit* pDateTimeEdit = new QDateTimeEdit(parent);
            pDateTimeEdit->setDateTime(variant.toDateTime());
            pDateTimeEdit->setCalendarPopup(true);
            pDateTimeEdit->setDisplayFormat(m_qsDataFormat);
            return pDateTimeEdit;
        }
        return QStyledItemDelegate::createEditor(parent, option, index);
    };
};

class QSqlRelationalTableModelEx : public QSqlRelationalTableModel
{
    Q_OBJECT

public:
    explicit QSqlRelationalTableModelEx(QObject *parent = nullptr,
                                        QSqlDatabase db = QSqlDatabase()):QSqlRelationalTableModel(parent, db){};

protected:
    QMap<int, QColor> m_relationTextColorMap;
    QList<QColor> m_colTextColor;

public:
    void InsertRelationTextColorMap(int column, QColor color){m_relationTextColorMap.insert(column, color);};
    void AppendcolTextColorList(QColor color){m_colTextColor.append(color);};

    // QAbstractItemModel interface
public:
    virtual QVariant data(const QModelIndex &index, int role) const override
    {
        if(role == Qt::TextAlignmentRole)
        {
            return Qt::AlignCenter;
        }
        else if(role == Qt::TextColorRole)
        {
            if(relation(index.column()).isValid())
            {
                QColor color = m_relationTextColorMap.value(index.column());
                if(color.isValid())
                {
                    return color;
                }
            }
            if(m_colTextColor.size() > index.column())
            {
                QColor color = m_colTextColor.at(index.column());
                if(color.isValid())
                {
                    return color;
                }
            }
        }
        return QSqlRelationalTableModel::data(index, role);
    };
};


class QViewObject : public QObject
{
    Q_OBJECT

public:
    QViewObject(QTableView* pTableView, QSqlRelationalTableModelEx* pSqlRelationalTableModel)
        :m_pTableView(pTableView), m_pSqlRelationalTableModel(pSqlRelationalTableModel)
        ,m_bAdd(false), m_bDel(false), m_bUpdate(false){};

private:
    QMenu m_menu;
    QTableView* m_pTableView;
    QSqlRelationalTableModelEx* m_pSqlRelationalTableModel;
    bool m_bAdd;
    bool m_bDel;
    bool m_bUpdate;
    QList<QAction *> m_ActionList;

public:
    void AddAction(QAction* pAction)
    {
        m_ActionList.append(pAction);
        this->connectViewClick();
    }
    void SetMode(bool bAdd = false, bool bDel=false, bool bUpdate = false)
    {
        m_bAdd = bAdd;
        m_bDel = bDel;
        m_bUpdate = bUpdate;
        if(m_bUpdate)
        {
            m_pTableView->setEditTriggers(QAbstractItemView::DoubleClicked);
        }
        else
        {
            m_pTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
        }
        this->connectViewClick();
    }
    void connectViewClick()
    {
        m_menu.clear();
        QAction *pActionRefresh= new QAction("刷新", this);
        m_menu.addAction(pActionRefresh);
        connect(pActionRefresh, &QAction::triggered, this, [&] {
            m_pSqlRelationalTableModel->select();
        });
        if(m_bAdd)
        {
            QAction *pActionAdd= new QAction("增加", this);
            m_menu.addAction(pActionAdd);
            connect(pActionAdd, &QAction::triggered, this, [&] {
                int rowCount = m_pSqlRelationalTableModel->rowCount();
                m_pSqlRelationalTableModel->insertRow(rowCount);
                //m_pSqlRelationalTableModel->setData(m_pSqlRelationalTableModel->index(rowCount, 0), "");
                m_pTableView->setEditTriggers(QTableView::DoubleClicked);
                m_pTableView->scrollToBottom();
            });
        }
        if(m_bDel)
        {
            QAction *pActionDel= new QAction("删除", this);
            m_menu.addAction(pActionDel);
            connect(pActionDel, &QAction::triggered, this, [&] {
                if (QMessageBox::warning(m_pTableView, "提示", "确定删除选中行?", QMessageBox::Yes, QMessageBox::No) == QMessageBox::No) {
                    m_pSqlRelationalTableModel->revertAll();
                    return;
                }
                QModelIndexList modelIndexList = m_pTableView->selectionModel()->selectedRows();
                foreach(QModelIndex modelIndex, modelIndexList)
                {
                    m_pSqlRelationalTableModel->removeRow(modelIndex.row());
                }
                m_pSqlRelationalTableModel->submitAll();
            });
        }
        if(m_bUpdate)
        {
            QAction *pActionUpdate= new QAction("保存", this);
            m_menu.addAction(pActionUpdate);
            connect(pActionUpdate, &QAction::triggered, this, [&] {
                m_pSqlRelationalTableModel->submitAll();
            });
        }
        if(m_bAdd || m_bDel || m_bUpdate)
        {
            QAction *pActionRevert= new QAction("撤销", this);
            m_menu.addAction(pActionRevert);
            connect(pActionRevert, &QAction::triggered, this, [&] {
                m_pSqlRelationalTableModel->revertAll();
            });
        }
        m_menu.addSeparator();
        foreach(QAction* pAction, m_ActionList)
        {
            m_menu.addAction(pAction);
        }
        connect(m_pTableView, &QTableView::customContextMenuRequested, this, [&]
        {
            m_menu.move(m_pTableView->cursor().pos());
            m_menu.show();
        });
    };
};

template<typename TEMP>
class QSqlRelationalTableModelView
{

public:
    QSqlRelationalTableModelView(QString qsTableName/*关联的表名*/, bool bCreatView = false/*是否创建界面类QTableView*/);
    ~QSqlRelationalTableModelView();

private:
    QTableView* m_pTableView;
    QViewObject* m_pViewObject;
    QSqlRelationalTableModelEx* m_pSqlRelationalTableModel;
    bool m_bView;//存在View
    QString m_qsTableName;
    MySqlOper* m_pMySqlOper;
    QList<TSerialisation> m_tSerialisationList;
    QList<QString> m_headList;
    QList<QString> m_headListTitle;
    QMap<int, QSqlRelationalTableModelView*> m_relationModelViewMap;
    QString m_qsDateFormat;

private:
    QSqlRelationalTableModelView*  findAndCreatRelationalTableModelView(int column);

protected:
    QList<TSerialisation> getSerialisationList(){return m_tSerialisationList;};
    QList<QString> getHeadList(){return m_headList;};
    QList<QString> getHeadListTitle(){return m_headListTitle;};
    QString getTableName(){return m_qsTableName;};
    QString getDateFormat(){return m_qsDateFormat;};

public:
    QTableView* GetTableView();//获得列表
    void SetRelation(int column/*当前表列号*/,
                     const QString &aTableName/*关联外键的父表名*/,
                     const QString &indexCol/*关联父表的字段名*/,
                     const QString &displayCol/*显示父表的字段名*/,
                     const QColor &colorCol = QColor()/*显示父表颜色,优先级高于显示颜色*/);//设置外键
    bool SQL_Init(QString csUser, QString csPasswd, QString csDB, QString csHost = "127.0.0.1", int nPort = 3306);//数据库初始化
    void SetSerialisationHead(const QString qsHead/*数据库表字段名*/, const QString qsHeadTitle/*列表头标题*/, TSerialisation tSerialisation, const QColor &colorCol = QColor()/*显示颜色*/);//设置序列化表头
    QList<TEMP> SQL_QueryData(QString csSql);//前提SetSerialisationHead必须按照表结构严格输入,否则请使用SQL_QuerySerialisation方法,Sql查询本表数据,返回本表字段必须是本表所有字段且不包含其他表字段
    char* SQL_QuerySerialisation(QString csSql, int& nQuerySize/*结果集个数*/, QList<TSerialisation> tSerialisationList = QList<TSerialisation>());//序列化查询数据库 需删除返回值
    void InitView();//初始化列表,如果不创建界面类QTableView无需调用
    QSqlRelationalTableModelEx* GetModel();//获得外键QSqlRelationalTableModelEx*
    void SetMode(bool bAdd = false, bool bDel=false, bool bUpdate = false);//设置列表的增删改是否可用
    void SetSortingEnabled(bool enable); //启用排序 默认是禁用排序的
    void AddAction(QAction* pAction);//添加自定义右键菜单
    QSqlTableModel *RelationModel(int column);//获得外键表模型
    void SetDateTimeFormat(QString qsDateFormat);//设置时间格式化格式

    /*外键列表函数*/
    QTableView* GetRelationTableView(int column);//获得外键列表
    QSqlRelationalTableModelEx* GetRelationModel(int column);//获得外键QSqlRelationalTableModelEx*
    void SetRelationModelHead(int column, const QString qsHead/*数据库表字段名*/, const QString qsHeadTitle/*列表头标题*/, const QColor &colorCol = QColor()/*显示颜色*/);//设置外键表表头
    void InitRelationView(int column);//初始化外键表列表
    void SetRelationMode(int column, bool bAdd = false, bool bDel=false, bool bUpdate = false);//设置列表的增删改是否可用
    void SetRelationSortingEnabled(int column, bool enable); //启用外键表排序 默认是禁用排序的
    void AddRelationAction(int column, QAction* pAction);//添加外键表自定义右键菜单
};

template <typename TEMP>
QSqlRelationalTableModelView<TEMP>::QSqlRelationalTableModelView(QString qsTableName, bool bCreatView)
    :m_bView(bCreatView), m_qsTableName(qsTableName)
{
    m_pMySqlOper = MySqlOper::GetInstance();
    m_pSqlRelationalTableModel = new QSqlRelationalTableModelEx(nullptr, *m_pMySqlOper->SQL_DataBase());
    if(m_bView)
    {
        m_pTableView = new QTableView;
        m_pViewObject = new QViewObject(m_pTableView, m_pSqlRelationalTableModel);
        m_pViewObject->connectViewClick();
    }
    m_qsDateFormat = "yyyy/MM/dd HH:mm:ss";
}

template<typename TEMP>
QSqlRelationalTableModelView<TEMP>::~QSqlRelationalTableModelView()
{
    if(m_pSqlRelationalTableModel != nullptr)
    {
        delete m_pSqlRelationalTableModel;
    }
    MySqlOper::ReleaseInstance();
}

template<typename TEMP>
QSqlRelationalTableModelView<TEMP> *QSqlRelationalTableModelView<TEMP>::findAndCreatRelationalTableModelView(int column)
{
    QSqlRelationalTableModelView* pSqlRelationalTableModelView = m_relationModelViewMap.value(column, nullptr);
    if(pSqlRelationalTableModelView == nullptr)
    {
        pSqlRelationalTableModelView = new QSqlRelationalTableModelView(RelationModel(column)->tableName(), true);
        pSqlRelationalTableModelView->SetDateTimeFormat(m_qsDateFormat);
    }
    m_relationModelViewMap.insert(column, pSqlRelationalTableModelView);
    return pSqlRelationalTableModelView;
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::InitView()
{
    if(m_pSqlRelationalTableModel != nullptr && m_pTableView != nullptr)
    {
        m_pTableView->setAlternatingRowColors(true);
        m_pTableView->setContextMenuPolicy(Qt::CustomContextMenu);
        m_pTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
        //        m_pTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);//自适应宽度
        m_pTableView->horizontalHeader()->setMinimumSectionSize(100);
        m_pTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter);
        m_pTableView->verticalHeader()->setDefaultAlignment(Qt::AlignCenter);
        m_pTableView->setModel(m_pSqlRelationalTableModel);
        for(int i = 0; i < m_tSerialisationList.size(); i++)
        {
            if(m_tSerialisationList.at(i).eType == eDateTime)
            {
                m_pTableView->setItemDelegateForColumn(i, new QDateTimeItemDelegate(m_qsDateFormat));
            }
        }
        m_pTableView->setItemDelegate(new QSqlRelationalDelegate(m_pTableView));
        m_pSqlRelationalTableModel->setTable(m_qsTableName);
        m_pSqlRelationalTableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);//编辑后需要Submit才能更改
        for(int i = 0; i < m_headList.size(); i++)
        {
            m_pSqlRelationalTableModel->setHeaderData(m_pSqlRelationalTableModel->fieldIndex(m_headList.at(i))
                                                      , Qt::Horizontal, m_headListTitle.at(i));
        }
        m_pSqlRelationalTableModel->select();
    }
}

template<typename TEMP>
QSqlRelationalTableModelEx *QSqlRelationalTableModelView<TEMP>::GetModel()
{
    return m_pSqlRelationalTableModel;
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::SetMode(bool bAdd, bool bDel, bool bUpdate)
{
    if(m_pViewObject != nullptr)
    {
        m_pViewObject->SetMode(bAdd, bDel, bUpdate);
    }
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::SetSortingEnabled(bool enable)
{
    if (m_pTableView != nullptr) {
        m_pTableView->setSortingEnabled(enable);
        m_pTableView->horizontalHeader()->setSortIndicator(0, Qt::AscendingOrder);
    }
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::AddAction(QAction *pAction)
{
    if(m_pViewObject != nullptr)
    {
        m_pViewObject->AddAction(pAction);
    }
}

template<typename TEMP>
QSqlTableModel *QSqlRelationalTableModelView<TEMP>::RelationModel(int column)
{
    if(m_pSqlRelationalTableModel != nullptr)
    {
        return m_pSqlRelationalTableModel->relationModel(column);
    }
    return nullptr;
}

template<typename TEMP>
QTableView *QSqlRelationalTableModelView<TEMP>::GetRelationTableView(int column)
{
    QSqlRelationalTableModelView* pSqlRelationalTableModelView = findAndCreatRelationalTableModelView(column);
    if(pSqlRelationalTableModelView != nullptr)
    {
        return pSqlRelationalTableModelView->GetTableView();
    }
    return nullptr;
}

template<typename TEMP>
QSqlRelationalTableModelEx *QSqlRelationalTableModelView<TEMP>::GetRelationModel(int column)
{
    QSqlRelationalTableModelView* pSqlRelationalTableModelView = findAndCreatRelationalTableModelView(column);
    if(pSqlRelationalTableModelView != nullptr)
    {
        return pSqlRelationalTableModelView->GetModel();
    }
    return nullptr;
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::SetRelationModelHead(int column, const QString qsHead, const QString qsHeadTitle, const QColor &colorCol)
{
    QSqlRelationalTableModelView* pSqlRelationalTableModelView = findAndCreatRelationalTableModelView(column);
    if(pSqlRelationalTableModelView != nullptr)
    {
        pSqlRelationalTableModelView->SetSerialisationHead(qsHead, qsHeadTitle, TSerialisation(eInt, sizeof(int))/*序列化无效,做SQL查询用*/, colorCol);
    }
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::InitRelationView(int column)
{
    QSqlRelationalTableModelView* pSqlRelationalTableModelView = findAndCreatRelationalTableModelView(column);
    if(pSqlRelationalTableModelView != nullptr && pSqlRelationalTableModelView->GetModel() != nullptr && pSqlRelationalTableModelView->GetTableView() != nullptr)
    {
        pSqlRelationalTableModelView->GetTableView()->setAlternatingRowColors(true);
        pSqlRelationalTableModelView->GetTableView()->setContextMenuPolicy(Qt::CustomContextMenu);
        pSqlRelationalTableModelView->GetTableView()->setSelectionBehavior(QAbstractItemView::SelectRows);
        //        pSqlRelationalTableModelView->GetTableView()->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);//自适应宽度
        pSqlRelationalTableModelView->GetTableView()->horizontalHeader()->setMinimumSectionSize(100);
        pSqlRelationalTableModelView->GetTableView()->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter);
        pSqlRelationalTableModelView->GetTableView()->verticalHeader()->setDefaultAlignment(Qt::AlignCenter);
        pSqlRelationalTableModelView->GetTableView()->setModel(pSqlRelationalTableModelView->GetModel());
        for(int i = 0; i < pSqlRelationalTableModelView->getSerialisationList().size(); i++)
        {
            if(pSqlRelationalTableModelView->getSerialisationList().at(i).eType == eDateTime)
            {
                pSqlRelationalTableModelView->GetTableView()->setItemDelegateForColumn(i, new QDateTimeItemDelegate(pSqlRelationalTableModelView->getDateFormat()));
            }
        }
        pSqlRelationalTableModelView->GetTableView()->setItemDelegate(new QSqlRelationalDelegate(pSqlRelationalTableModelView->GetTableView()));
        pSqlRelationalTableModelView->GetModel()->setTable(pSqlRelationalTableModelView->getTableName());
        pSqlRelationalTableModelView->GetModel()->setEditStrategy(QSqlTableModel::OnManualSubmit);//编辑后需要Submit才能更改
        for(int i = 0; i < pSqlRelationalTableModelView->getHeadList().size(); i++)
        {
            pSqlRelationalTableModelView->GetModel()->setHeaderData(pSqlRelationalTableModelView->GetModel()->fieldIndex(pSqlRelationalTableModelView->getHeadList().at(i))
                                                                    , Qt::Horizontal, pSqlRelationalTableModelView->getHeadListTitle().at(i));
        }
        pSqlRelationalTableModelView->GetModel()->select();
    }
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::SetRelationMode(int column, bool bAdd, bool bDel, bool bUpdate)
{
    QSqlRelationalTableModelView* pSqlRelationalTableModelView = findAndCreatRelationalTableModelView(column);
    if(pSqlRelationalTableModelView != nullptr)
    {
        pSqlRelationalTableModelView->SetMode(bAdd, bDel, bUpdate);
    }
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::SetRelationSortingEnabled(int column, bool enable)
{
    QSqlRelationalTableModelView* pSqlRelationalTableModelView = findAndCreatRelationalTableModelView(column);
    if(pSqlRelationalTableModelView != nullptr)
    {
        pSqlRelationalTableModelView->SetSortingEnabled(enable);
    }
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::AddRelationAction(int column, QAction *pAction)
{
    QSqlRelationalTableModelView* pSqlRelationalTableModelView = findAndCreatRelationalTableModelView(column);
    if(pSqlRelationalTableModelView != nullptr)
    {
        pSqlRelationalTableModelView->AddAction(pAction);
    }
}

template<typename TEMP>
QTableView *QSqlRelationalTableModelView<TEMP>::GetTableView()
{
    return m_pTableView;
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::SetRelation(int column, const QString &aTableName, const QString &indexCol,
                                                     const QString &displayColconst, const QColor &colorCol)
{
    if(m_pSqlRelationalTableModel != nullptr)
    {
        m_pSqlRelationalTableModel->setRelation(column, QSqlRelation(aTableName, indexCol, displayColconst));
        m_pSqlRelationalTableModel->InsertRelationTextColorMap(column, colorCol);
    }
}

template<typename TEMP>
bool QSqlRelationalTableModelView<TEMP>::SQL_Init(QString csUser, QString csPasswd, QString csDB, QString csHost, int nPort)
{
    m_pMySqlOper->SQL_SetPro(csUser, csPasswd, csDB, csHost, nPort);
    return m_pMySqlOper->SQL_Connect();
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::SetSerialisationHead(const QString qsHead, const QString qsHeadTitle, TSerialisation tSerialisation, const QColor &colorCol)
{
    m_headList.append(qsHead);
    m_headListTitle.append(qsHeadTitle);
    m_tSerialisationList.append(tSerialisation);
    GetModel()->AppendcolTextColorList(colorCol);
}

template<typename TEMP>
char *QSqlRelationalTableModelView<TEMP>::SQL_QuerySerialisation(QString csSql, int& nQuerySize, QList<TSerialisation> tSerialisationList)
{
    return m_pMySqlOper->SQL_QuerySerialisation(csSql, nQuerySize, tSerialisationList);
}

template<typename TEMP>
QList<TEMP> QSqlRelationalTableModelView<TEMP>::SQL_QueryData(QString csSql)
{
    int nQuerySize = 0;
    char* p = m_pMySqlOper->SQL_QuerySerialisation(csSql, nQuerySize, m_tSerialisationList);
    QList<TEMP> resultList;
    if(p != nullptr && nQuerySize > 0)
    {
        TEMP* pTemp = (TEMP*)p;
        for(int i = 0; i < nQuerySize; i++)
        {
            TEMP temp;
            memcpy(&temp, &pTemp[i], sizeof (TEMP));
            resultList.append(temp);
        }
        delete [] p;
    }
    return resultList;
}

template<typename TEMP>
void QSqlRelationalTableModelView<TEMP>::SetDateTimeFormat(QString qsDateFormat)
{
    m_qsDateFormat  = qsDateFormat;
}
#endif // QSQLRELATIONALTABLEMODELVIEW_H

//使用方法
//xxx.h
#pragma pack(push,1)//按字节对齐begin

struct tTemp{
    int id;
    int EInt;
    float EFloat;
    double EDouble;
    qint64 EDateTime;
};

struct tTempJoin{
    int id;
    char EString1[255];
    char EString2[255];
    double EDouble;
    qint64 EDateTime;
};
#pragma pack(pop)//按字节对齐end

private:
    QSqlRelationalTableModelView<tTemp>* m_pSqlRelationalTableModelView;

//xxx.cpp
static bool bCreat = false;
        if(!bCreat)
        {
            /*表结构
            CREATE TABLE `ModelTest` (
              `id` int NOT NULL AUTO_INCREMENT,
              `EInt` int NOT NULL,
              `EFloat` float NOT NULL,
              `EDouble` double NOT NULL,
              `EDateTime` datetime NOT NULL,
              PRIMARY KEY (`id`),
              KEY `name` (`EInt`) USING BTREE,
              KEY `name2` (`EFloat`),
              CONSTRAINT `name` FOREIGN KEY (`EInt`) REFERENCES `DICT` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
              CONSTRAINT `name2` FOREIGN KEY (`EFloat`) REFERENCES `DICT2` (`id`)
            );
            CREATE TABLE `DICT` (
              `id` int NOT NULL,
              `name` varchar(255) NOT NULL,
              KEY `id` (`id`)
            );
            CREATE TABLE `DICT2` (
              `id` float NOT NULL,
              `name` varchar(255) NOT NULL,
              KEY `id` (`id`)
            )
            */
            m_pSqlRelationalTableModelView = new QSqlRelationalTableModelView<tTemp>("ModelTest", true);
            m_pSqlRelationalTableModelView->SQL_Init("root", "0000", "RadioMonitor");
            m_pSqlRelationalTableModelView->SetSerialisationHead("id", "序号", TSerialisation(eInt, sizeof(int)));
            m_pSqlRelationalTableModelView->SetSerialisationHead("EInt", "Int值", TSerialisation(eInt, sizeof(int)));
            m_pSqlRelationalTableModelView->SetSerialisationHead("EFloat", "Float值", TSerialisation(eFloat, sizeof(float)));
            m_pSqlRelationalTableModelView->SetSerialisationHead("EDouble", "Double值", TSerialisation(eDouble, sizeof(double)));
            m_pSqlRelationalTableModelView->SetSerialisationHead("EDateTime", "DateTime值", TSerialisation(eDateTime, sizeof(qint64)));
            m_pSqlRelationalTableModelView->InitView();
            m_pSqlRelationalTableModelView->SetRelation(1, "DICT","id","name", QColor(0, 255, 0));
            m_pSqlRelationalTableModelView->SetRelation(2, "DICT2","id","name", QColor(255, 255, 0));
            m_pSqlRelationalTableModelView->GetTableView()->resize(600, 300);
            m_pSqlRelationalTableModelView->SetMode(true, true, true);
            m_pSqlRelationalTableModelView->SetSortingEnabled(true);
            m_pSqlRelationalTableModelView->GetTableView()->setWindowTitle("数据库示例");

            //创建外键表1
            m_pSqlRelationalTableModelView->SetRelationModelHead(1, "id", "序号");
            m_pSqlRelationalTableModelView->SetRelationModelHead(1, "name", "名称");
            m_pSqlRelationalTableModelView->InitRelationView(1);
            m_pSqlRelationalTableModelView->GetRelationTableView(1)->resize(300, 150);
            m_pSqlRelationalTableModelView->SetRelationMode(1, true, true, true);
            m_pSqlRelationalTableModelView->SetRelationSortingEnabled(1, true);
            m_pSqlRelationalTableModelView->GetRelationTableView(1)->setWindowTitle("外键表1示例");
            //m_pSqlRelationalTableModelView->GetRelationModel(1)->setFilter("id=1");//设置过滤

            //创建外键表2
            m_pSqlRelationalTableModelView->SetRelationModelHead(2, "id", "序号");
            m_pSqlRelationalTableModelView->SetRelationModelHead(2, "name", "名称");
            m_pSqlRelationalTableModelView->InitRelationView(2);
            m_pSqlRelationalTableModelView->GetRelationTableView(2)->resize(300, 150);
            m_pSqlRelationalTableModelView->SetRelationMode(2, true, true, true);
            m_pSqlRelationalTableModelView->SetRelationSortingEnabled(2, true);
            m_pSqlRelationalTableModelView->GetRelationTableView(2)->setWindowTitle("外键表2示例");
            //m_pSqlRelationalTableModelView->GetRelationModel(2)->setFilter("id=1");//设置过滤

            //自定义右键菜单
            QAction *pAction1= new QAction("外键列表1示例", this);
            connect(pAction1, &QAction::triggered, this, [&] {
                const QRect screen = QGuiApplication::screens().at(0)->geometry();
                m_pSqlRelationalTableModelView->GetRelationTableView(1)->move(screen.center() - m_pSqlRelationalTableModelView->GetRelationTableView(1)->rect().center());
                m_pSqlRelationalTableModelView->GetRelationTableView(1)->show();
            });
            m_pSqlRelationalTableModelView->AddAction(pAction1);

            QAction *pAction2= new QAction("外键列表2示例", this);
            connect(pAction2, &QAction::triggered, this, [&] {
                const QRect screen = QGuiApplication::screens().at(0)->geometry();
                m_pSqlRelationalTableModelView->GetRelationTableView(2)->move(screen.center() - m_pSqlRelationalTableModelView->GetRelationTableView(1)->rect().center());
                m_pSqlRelationalTableModelView->GetRelationTableView(2)->show();
            });
            m_pSqlRelationalTableModelView->AddAction(pAction2);

            const QRect screen = QGuiApplication::screens().at(0)->geometry();
            m_pSqlRelationalTableModelView->GetTableView()->move(screen.center() - m_pSqlRelationalTableModelView->GetTableView()->rect().center());
            //默认查询,SQL语句需返回本表所有字段且不含其他表字段
            QList<tTemp> list= m_pSqlRelationalTableModelView->SQL_QueryData("SELECT * FROM ModelTest LIMIT 0,100");
            qDebug() << list.size();
            //INNER JOIN查询 或者 LEFT JOIN查询
            QList<TSerialisation> tSerialisationList;
            tSerialisationList << TSerialisation(eInt, sizeof(int));
            tSerialisationList << TSerialisation(eString, 255);
            tSerialisationList << TSerialisation(eString, 255);
            tSerialisationList << TSerialisation(eDouble, sizeof(double));
            tSerialisationList << TSerialisation(eDateTime, sizeof(qint64));
            int nQuerySize = 0;
            tTempJoin* ptTempJoin= (tTempJoin*)m_pSqlRelationalTableModelView->SQL_QuerySerialisation(
                        "SELECT a.id, b.name, c.name, a.EDouble, a.EDateTime FROM ModelTest a INNER JOIN DICT b, DICT2 c LIMIT 0,100", nQuerySize, tSerialisationList);
            if(nQuerySize > 1)
                qDebug() << nQuerySize << ptTempJoin[0].EString1 << ptTempJoin[0].EString2;
            else
                qDebug() << nQuerySize;
        }
        m_pSqlRelationalTableModelView->GetTableView()->show();
        bCreat = true;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/85170.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

LION AI 大模型落地,首搭星纪元 ES

自新能源汽车蓬勃发展以来&#xff0c;随着潮流不断进步和变革的“四大件”有着明显变化。其中有&#xff1a;平台、智能驾驶、配置、以及车机。方方面面都有着不同程度的革新。 而车机方面&#xff0c;从以前老旧的媒体机、 CD 机发展至如今具有拓展性、开放性、智能化的车机…

【xxl-job快速入门搭建】

目录标题 xxl-job快速入门搭建源码地址项目结构初始化数据库启动项目1、启动服务端2、启动任务执行器端 MD文档指导教程功能快捷键合理的创建标题&#xff0c;有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内…

RISC-V公测平台发布 · 数据库在RISC-V服务器上的适配评估

前言 上一期讲到YCSB在RISC-V服务器上对MySQL进行性能测试&#xff08;RISC-V公测平台发布 使用YCSB测试SG2042上的MySQL性能&#xff09;&#xff0c;在这一期文章中&#xff0c;我们继续深入讨论RISC-V数据库的应用。本期就继续利用HS-2平台来测试数据库软件在RISC-V服务器…

神经网络为什么可以学习

本资料转载于B站up主&#xff1a;大模型成长之路,仅用于学习和讨论&#xff0c;如有侵权请联系 动画解析神经网络为什么可以学习_哔哩哔哩_bilibilis 1、一个神经网络是由很多神经元形成的 1.1 也可以是一层&#xff0c;也可以是多层 2 层和层之间的连接就跟一张网一样 2.1 每…

python35种绘图函数总结,3D、统计、流场,实用性拉满

文章目录 基础图误差线三维图等高线图场图统计图非结构坐标图 基础图 下面这8种图像一般只有两组坐标&#xff0c;直观容易理解。 函数坐标参数图形类别plotx,y曲线图stackplotx,y散点图stemx,y茎叶图scatterx,y散点图polarx,y极坐标图stepx,y步阶图barx,y条形图barhx,y横向条…

excel导入导出百万级数据优化

背景 在我前年找实习的时候&#xff0c;遇到了面试官问我&#xff1a;mysql从excel导出百万级数据&#xff0c;该怎么做&#xff1f;我听到的第一反应是&#xff1a;我*&#xff0c;我哪去接触百万级的数据&#xff0c;你们导出的数据是什么&#xff1f;我还是一个才找实习工作…

python实战【外星人入侵】游戏并改编为【梅西vsC罗】(球迷整活)——搭建环境、源码、读取最高分及生成可执行的.exe文件

文章目录 &#x1f3a5;前言&#x1f4bc;安装Pygame&#x1f50b;游戏的实现读写并存储【外星人入侵】游戏最高分游戏源码alien_invasion.pygame_functions.pyship.pyalien.pybullet.pybutton.pyscoreboard.pygame_stats.pysettings.py宇宙飞船和外星人的 .bmp类型文件 &#…

Go语言入门指南:基础语法和常用特性(下)

上一节&#xff0c;我们了解Go语言特性以及第一个Go语言程序——Hello World&#xff0c;这一节就让我们更深入的了解一下Go语言的**基础语法**吧&#xff01; 一、行分隔符 在 Go 程序中&#xff0c;一行代表一个语句结束。每个语句不需要像 C 家族中的其它语言一样以分号 ;…

解决IDEA tomcat控制台只有server日志

解决IDEA tomcat控制台只有server日志 确认tomcatxxx/conf/logging.properties文件是否存在&#xff0c;存在就会有。前提是在run configuration配置了打印多个日志

K8s+Docker+KubeSphere+DevOps笔记

K8sDockerKubeSphereDevOps 前言一、阿里云服务器开通二、docker基本概念1.一次构建、到处运行2、docker基础命令操作3、docker进阶操作1.部署redis中间件2.打包docker镜像 三、kubernetes 大规模容器编排系统1、基础概念&#xff1a;1、服务发现和负载均衡2、存储编排3、自动部…

概率论与数理统计:第七章:参数估计 第八章:假设检验

文章目录 Ch7. 参数估计7.1 点估计1.矩估计2.最大似然估计(1)离散型(2)连续型 7.2 评价估计量优良性的标准(1)无偏性 (无偏估计)(2)有效性(3)一致性 7.3 区间估计1.置信区间、置信度2.求μ的置信区间 Ch8. 假设检验1.拒绝域α、接受域1-α、H₀原假设、H₁备择假设2.双边检验、…

操作符详解(2)

9.条件操作符 由问号和冒号组成&#xff0c;有三个表达式&#xff0c;有三个操作符&#xff0c;所以条件操作符是唯一的一个三目操作符&#xff0c;exp1为真&#xff0c;exp2则计算&#xff0c;exp3不算&#xff0c;整个表达式的结果就是exp2的结果。exp1为假&#xff0c;exp2…

【M波段2D双树(希尔伯特)小波多分量图像去噪】基于定向M波段双树(希尔伯特)小波对多分量/彩色图像进行降噪研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

如何使用CSS实现一个瀑布流布局?

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ 使用CSS实现瀑布流布局⭐ 写在最后 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 记得点击上方或者右侧链接订阅本专栏哦 几何带你启航前端之旅 欢迎来到前端入门之旅&#xff01;这个专栏是为那些对Web开发感兴趣、刚刚…

qiiuzhiji4

本篇是从慧与离职后到2023年8月21日这段时间的经历 2023/7/31至2023/8/21 本篇初次写于2023年8月21日 从慧与离职后基本上就是在专心找工作了&#xff0c;但是有在这段时间找工作经历的人都明白&#xff0c;IT行业不复以往了。尤其是对于我这样的普通二本学历的人来说&#xff…

阿里云席明贤:明天的视频云2.0

编者按 本文是“解构多媒体新常态”系列文章的第二篇&#xff0c;LiveVideoStack对话了阿里云视频云负责人席明贤&#xff08;花名右贤&#xff09;。面对风云变幻的内外环境&#xff0c;阿里云在视频云赛道是坚定向前的&#xff0c;在与右贤的接触中&#xff0c;他给我留下非常…

ZLMediakit-method ANNOUNCE failed: 401 Unauthorized

使用ffmpeg推流&#xff1a; nohup ffmpeg -stream_loop -1 -re -i "/usr/local/mp4/test.mp4" -vcodec h264 -acodec aac -f rtsp -rtsp_transport tcp rtsp://10.55.134.12/live/test &[rootlocalhost ~]# ffmpeg -stream_loop -1 -re -i "/usr/local/mp…

SpringBoot+WebSocket搭建多人在线聊天环境

一、WebSocket是什么&#xff1f; WebSocket是在单个TCP连接上进行全双工通信的协议&#xff0c;可以在服务器和客户端之间建立双向通信通道。 WebSocket 首先与服务器建立常规 HTTP 连接&#xff0c;然后通过发送Upgrade标头将其升级为双向 WebSocket 连接。 WebSocket使得…

Vue2入门学习汇总

1.介绍及安装 1.1 介绍 Vue是一套构建用户界面的渐进式框架。Vue只关注视图层&#xff0c;采用自底向上增量开发的设计。Vue的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。 学习vue之前主要掌握的知识&#xff1a;HTML、CSS、JavaScript、TypeScript …

基于PyQt+mysql图书管理系统

1 需求分析 针对图书馆的图书管理系统数据库设计&#xff0c;分别对图书馆的读者、一般工作人员和部门负责人进行详细地分析&#xff0c;总结出如下的需求信息: &#xff08;1&#xff09;图书馆中的图书具有书号、书名、作者、馆藏册数、在馆册数、价格、出版社及摘要等必要信…