QT-Mysql数据库图形化接口

news2024/11/13 9:24:37

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;

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ipadOS External cameras

必须是USB-C接口&#xff0c;所以在使用的时候需要确认USB video Class(UVC) 好像也可以使用HDMI AVFoundation 用于处理一批视频多媒体数据的创建&#xff0c;编辑&#xff0c;播放和捕获&#xff0c;时音频视频功能的基础库。 有什么功能呢&#xff1a; 1.可以支持多种音频…

RocketMQ(模式详解,安装)及控制台安装

下载 环境 64位操作系统&#xff0c;推荐 Linux/Unix/macOS 64位 JDK 1.8下载地址 https://rocketmq.apache.org/zh/download/ RocketMQ 的安装包分为两种&#xff0c;二进制包和源码包。 二进制包是已经编译完成后可以直接运行的&#xff0c;源码包是需要编译后运行的。 单…

【Android】解决Lint found fatal errors while assembling a release target

报错信息&#xff1a; Android在debug模式下打包没有问题&#xff0c;但是在打包release版本时出现一下问题&#xff1a; 结果图 原因 我项目的原因是因为把正式、测试地址放到代码里了&#xff0c;忘记选中正式环境的地址&#xff0c;导致打正式包有问题&#xff1b;大家如果…

ASEMI肖特基模块MBR400100CT参数规格

编辑-Z MBR400100CT参数描述&#xff1a; 型号&#xff1a;MBR400100CT 反向重复峰值电压(VRRM)&#xff1a;100V 正向直流电流(I0)&#xff1a;400A 正向&#xff08;不重复&#xff09;浪涌电流(IFSM)&#xff1a;3300A 结温 (TJ)&#xff1a;-40 to 175℃ 储存温度(T…

mybatis生命周期和作用域

前言 作用域和生命周期错误使用会导致并发问题。 mybatis执行过程&#xff1a; 1、SqlSessionFactoryBuilder SqlSessionFactoryBuilder 占用XML资源来创建多个 SqlSessionFactory实例&#xff1b; SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域&#xff08;也就…

MBSE项目的全新数据、信息与知识管理方法|数据模型标准化思路

仅供学习使用 An original Data, Information and Knowledge management approach for model-based engineering projects 作者&#xff1a;M. El Alaoui, S. Rabah, V. Chapurlat, V. Richet , R. Plana 来源&#xff1a;https://doi.org/10.1016/j.ifacol.2022.10.135 文章详…

强化学习A3C算法

强化学习A3C算法 效果&#xff1a; a3c.py import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams[font.size] 18 matplotlib.rcParams[figure.titlesize] 18 matplotlib.rcParams[figure.figsize] [9, 7] matplotlib.rcParams[font.family]…

谓语动词(动词不定式(短语)、动名词、分词(短语))作定语

动词不定式(短语)作定语 动名词作定语 分词&#xff08;短语&#xff09;作定语 着重记忆及物动词

剑指offer-2.2字符串

字符串 C/C中每个字符串都以字符"\0"作为结尾&#xff0c;这样我们就能很方便地找到字符串的最后尾部。但由于这个特点&#xff0c;每个字符串中都有一个额外字符的开销&#xff0c;稍不留神就会造成字符串的越界。比如下面的代码&#xff1a; char str [10]; strc…

UWB现场安装通常涉及以下步骤

UWB现场安装通常涉及以下步骤&#xff1a; 1.确定区域需求&#xff1a;首先&#xff0c;确定需要进行UWB定位的区域和目标。这可能是一个室内环境、仓库、工厂或其他特定的工作场所。 2.设计系统布局&#xff1a;根据区域的特点和目标定位需求&#xff0c;设计系统的布局和基…

关于Firmae缺失binwalk模块

问题 david707:~/FirmAE$ sudo ./run.sh -c weyow ./WAM_9900-20.06.03V.trx [*] ./WAM_9900-20.06.03V.trx emulation start!!! Traceback (most recent call last):File "./sources/extractor/extractor.py", line 19, in <module>import binwalk ModuleNot…

红帽8.2版本CSA题库:第十题配置用户帐户

红帽8.2版本CSA题库&#xff1a;第十题配置用户帐户 useradd -u 3533 manalo #传创建用户指定uid为3533 echo flectrag | passwd --stdin manalo #设置密码 tail -1 /etc/passwd #查看

globals()与locals()函数

在Python中&#xff0c;globals()和locals()是两个内置函数&#xff0c;用于获取当前作用域内的全局和局部命名空间中的变量和对象。 一、globals() :这个函数返回一个包含当前全局作用域中所有变量和对象的字典。在函数内部调用globals()将返回全局命名空间中的变量&#xf…

密码湘军,融合创新!麒麟信安参展2023商用密码大会,铸牢数据安全坚固堡垒

2023年8月9日至11日&#xff0c;商用密码大会在郑州国际会展中心正式开幕。本次大会由国家密码管理局指导&#xff0c;中国密码学会支持&#xff0c;郑州市人民政府、河南省密码管理局主办&#xff0c;以“密码赋能美好发展”为主题&#xff0c;旨在推进商用密码创新驱动、前沿…

2023年第四届全国人工智能大赛初赛晋级复赛名单公示

由深圳市科技创新委员会、鹏城实验室共同主办&#xff0c;新一代人工智能产业技术创新战略联盟&#xff08;AITISA&#xff09;承办&#xff0c;华为技术有限公司、中国工商银行股份有限公司深圳市分行、中国农业银行股份有限公司深圳市分行、中国建设银行股份有限公司深圳市分…

无线测温产品在半导体制造项目的应用

摘 要&#xff1a;半导体被誉为“制造业的大脑”&#xff0c;在关系国家安全和国民经济命脉的主要行业和关键领域占据支配地位&#xff0c;是国民经济的重要支柱。 随着数字技术的发展和数字经济在国民经济中所占比重越来越高&#xff0c;半导体产业的重要性还会进一步提升。安…

【制作npm包4】api-extractor 学习

制作npm包目录 本文是系列文章&#xff0c; 作者一个橙子pro&#xff0c;本系列文章大纲如下。转载或者商业修改必须注明文章出处 一、申请npm账号、个人包和组织包区别 二、了解 package.json 相关配置 三、 了解 tsconfig.json 相关配置 四、 api-extractor 学习 五、npm包…

高等数学教材啃书汇总重难点(三)微分中值定理与导数的应用

本章节包含多个知识点&#xff0c;一些列微分中值定理是考研证明题的重头戏&#xff0c;而洛必达和泰勒展开则是方法论的天花板难度&#xff0c;虽然对于小题的考察难度较低&#xff0c;整体上仍需重点复习 1.费马引理 2.罗尔定理 3.拉格朗日定理 4.柯西中值定理 5.洛必达法则 …

算法竞赛入门【码蹄集新手村600题】(MT1160-1180)C语言

算法竞赛入门【码蹄集新手村600题】(MT1160-1180&#xff09;C语言 目录MT1161 N的零MT1162 数组最大公约数MT1163 孪生质数MT1164 最大数字MT1165 卡罗尔数MT1166 自守数MT1167自守数IIMT1168 阶乘数MT1169 平衡数MT1170 四叶玫瑰数MT1171 幻数MT1172 完美数字MT1173 魔数MT11…

ODB++资料解析

ODB文件是由VALOR提出的一种ASCII码&#xff0c;双向传输文件。奥宝公司和康代公司的设备都是用的ODB格式进行PCB的生产和检测。 对ODB文件进行解析把数据栅格化很重要&#xff0c;查了网上找不到一个成熟能用的ODB文件解析代码。自己上手写了一个。 当前解析一些载板&#x…