增加表tableview

main
hkc320 2024-09-12 16:23:44 +08:00
parent 2350667f99
commit d4191b4daf
14 changed files with 624 additions and 31 deletions

View File

@ -0,0 +1,22 @@
#include "datafetcher.h"
#include "globalparameters.h"
DataFetcher::DataFetcher()
{
}
DataFetcher::~DataFetcher()
{
}
bool DataFetcher::Fetch(TableData& tbl_data)
{
return true;
}
int DataFetcher::VerifyStatus()
{
return STATUS_NORMAL;
}

View File

@ -0,0 +1,19 @@
#ifndef DATAFETCHER_H
#define DATAFETCHER_H
#include "globalparameters.h"
class DataFetcher
{
public:
DataFetcher();
virtual ~DataFetcher();
public:
virtual bool Fetch(TableData& tbl_data);
protected:
int VerifyStatus();
};
#endif // DATAFETCHER_H

View File

@ -0,0 +1,125 @@
#include "devicepropertypage.h"
#include <QGuiApplication>
#include <QTimer>
#include <QMessageBox>
#include <QTableView>
#include <QVBoxLayout>
#include <QPushButton>
#include <QScrollBar>
#include "globalparameters.h"
#include "mytablemodel.h"
DevicePropertyPage::DevicePropertyPage(QWidget *parent) :
QWidget(parent),m_pTableView(nullptr),m_pButton(nullptr)
{
//InitializeTable();
m_pTimer = new QTimer(this);
connect(m_pTimer, SIGNAL(timeout()), this, SLOT(handleTimeout()));
//m_pTimer->start(AppData::getInstance()->nTimeOut);
}
DevicePropertyPage::~DevicePropertyPage()
{
}
void DevicePropertyPage::handleTimeout()
{
if(m_pTimer->isActive())
{
m_pTimer->stop();
Refresh();
int nInterval = 5000; //ui->spinBox->value();
m_pTimer->start(nInterval*1000);
}
}
void DevicePropertyPage::InitializeTable()
{
m_myModel = new MyTableModel(this);
m_myModel->setHeadData(AppData::getInstance()->lstDataTableHeaderText);
m_pTableView = new QTableView(this);
m_pButton = new QPushButton(tr("Refresh"), this);
// 创建主布局
QVBoxLayout *mainLayout = new QVBoxLayout(this);
//AppCommon::getInstance()->InitializeTableView(m_myModel,m_pTableView);
m_pTableView->setModel(m_myModel);
// 自动调整列宽
connect(m_pTableView->horizontalScrollBar(), &QScrollBar::valueChanged, this, &DevicePropertyPage::adjustColumnWidths);
adjustColumnWidths(); // 初次设置列宽
mainLayout->addWidget(m_pTableView);
// 创建一个水平布局来包含按钮
QHBoxLayout *buttonLayout = new QHBoxLayout();
buttonLayout->addStretch(); // 让按钮保持在右侧
buttonLayout->addWidget(m_pButton);
buttonLayout->setContentsMargins(0, 0, 0, 0); // 取消按钮的边距
// 将表格视图和按钮布局添加到主布局
mainLayout->addLayout(buttonLayout);
mainLayout->setContentsMargins(0, 0, 0, 0); // 取消主布局的边距
mainLayout->setSpacing(10); // 取消布局间的间距
// 设置固定大小和位置的按钮
m_pButton->setFixedSize(100, 30); // 设置按钮的固定大小
// 连接信号和槽
connect(m_pTableView, &QTableView::doubleClicked, this, &DevicePropertyPage::onTableViewDoubleClicked);
connect(m_pButton, &QPushButton::clicked, this, &DevicePropertyPage::onButtonClicked);
}
void DevicePropertyPage::Refresh()
{
QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
TableData tbl_data;
if (Fetch(tbl_data))
{
m_myModel->setModelData(tbl_data);
}
QGuiApplication::restoreOverrideCursor();
}
void DevicePropertyPage::setBaseType(unsigned int base, unsigned int mask)
{
filterBaseType = base;
mask_code = mask;
}
void DevicePropertyPage::onButtonClicked()
{
m_pTimer->stop();
Refresh();
}
void DevicePropertyPage::onTableViewDoubleClicked(const QModelIndex &index)
{
//QAbstractItemModel *model=ui->tableView->model();
MyTableModel *model = (MyTableModel *)m_pTableView->model();
QModelIndex mindex = model->index(index.row(),7); //index.row()为算选择的行号。7为所选中行的第8列。。
QVariant datatemp=model->data(mindex);
}
void DevicePropertyPage::adjustColumnWidths()
{
int columnCount = m_pTableView->model()->columnCount();
int totalWidth = m_pTableView->viewport()->width();
int columnWidth = totalWidth / columnCount;
for (int column = 0; column < columnCount; ++column)
{
m_pTableView->setColumnWidth(column, columnWidth);
}
}

View File

@ -0,0 +1,51 @@
#ifndef DEVICEPROPERTYPAGE_H
#define DEVICEPROPERTYPAGE_H
#pragma execution_character_set("utf-8")
#include <QWidget>
#include "datafetcher.h"
class MyTableModel;
class QTimer;
class QTableView;
class QPushButton;
class DevicePropertyPage : public QWidget,public DataFetcher
{
Q_OBJECT
public:
explicit DevicePropertyPage(QWidget *parent = nullptr);
~DevicePropertyPage();
void setBaseType(unsigned int base,unsigned int mask);
void InitializeTable();
public slots:
void handleTimeout(); //超时处理函数
private:
QTimer *m_pTimer;
private:
MyTableModel* m_myModel;
protected:
void Refresh();
private slots:
void onButtonClicked();
void onTableViewDoubleClicked(const QModelIndex &index);
void adjustColumnWidths();
private:
unsigned int filterBaseType;
unsigned int mask_code;
QTableView* m_pTableView;
QPushButton* m_pButton;
};
#endif // DEVICEPROPERTYPAGE_H

View File

@ -39,13 +39,22 @@ win32:LIBS += Ws2_32.lib
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
datafetcher.cpp \
devicepropertypage.cpp \
globalparameters.cpp \
main.cpp \
maindialog.cpp \
mainwindow.cpp
mainwindow.cpp \
mytablemodel.cpp
HEADERS += \
datafetcher.h \
devicepropertypage.h \
globalparameters.h \
maindialog.h \
mainwindow.h
mainwindow.h \
mytablemodel.h \
singleton.h
FORMS += \
maindialog.ui \

View File

@ -0,0 +1,96 @@
#include <QCoreApplication>
#include <QMessageBox>
#include <QString>
#include <QAbstractTableModel>
#include <QTableView>
#include <QHeaderView>
#include <QApplication>
#include <QCursor>
#include "globalparameters.h"
#include "mytablemodel.h"
AppData::~AppData()
{
}
AppData::AppData(token)
{
lstDataTableHeaderText << ("Status")
<< ("Parameter")
<< ("Value")
<< ("Unit")
<< ("Time");
nTimeOut = 5000;
qsDestinationIp = "127.0.0.1";
qsLastErrorString = "OK";
}
AppCommon::AppCommon(token)
{
}
AppCommon::~AppCommon()
{
}
void AppCommon::InitializeTableView(MyTableModel *model, QTableView *tableView)
{
//设置tableview的model
model->setHeadData(AppData::getInstance()->lstDataTableHeaderText);
tableView->setModel(model);
//tableView->horizontalHeader()->setStyleSheet("QHeaderView::section {color: black;padding-left: 4px;border: 1px solid #6c6c6c;}");
tableView->horizontalHeader()->setStyleSheet("QHeaderView::section{background:lightgray;}");
//tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); //Stretch
//点击表时不对表头行光亮(获取焦点)
tableView->horizontalHeader()->setHighlightSections(false);
tableView->horizontalHeader()->setDefaultSectionSize(35);
tableView->verticalHeader()->setDefaultSectionSize(30); //行高
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::SingleSelection);
tableView->setAlternatingRowColors(true);
tableView->setTextElideMode(Qt::ElideMiddle);
// //设置表头字体加粗
// QFont font = tableView->horizontalHeader()->font();
// font.setBold(true);
// tableView->horizontalHeader()->setFont(font);
//设置表头字体
tableView->horizontalHeader()->setFont(QFont("Arial", 12));
//所有单元格的字体 设置成一样
tableView->setFont(QFont("Arial", 9));
//设置表格数据区内的所有单元格都不允许编辑
tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
//设置列宽
int w = tableView->width();
int base = w /(AppData::getInstance()->lstDataTableHeaderText.count()-1);
tableView->setColumnWidth(0,base-45);
tableView->setColumnWidth(1,base-20);
tableView->setColumnWidth(2,base+30);
tableView->setColumnWidth(3,base+10);
tableView->setColumnWidth(4,base);
tableView->show();
}
CWaitorCursor::CWaitorCursor()
{
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
}
CWaitorCursor::~CWaitorCursor()
{
QApplication::restoreOverrideCursor();
}

View File

@ -0,0 +1,78 @@
#ifndef GLOBALPARAMETERS_H
#define GLOBALPARAMETERS_H
#pragma execution_character_set("utf-8")
#include <QStringList>
#include "singleton.h"
class QAbstractTableModel;
class QTableView;
class MyTableModel;
//采集设备参数所处的状态
typedef enum _tagSignalStatus
{
STATUS_NORMAL = 0,
STATUS_WARN = 1,
STATUS_ERROR = 2,
STATUS_INFO = 3,
}SignalStatus;
typedef struct _ModelItem
{
SignalStatus status;
std::string ParameterName;
std::string value;
std::string unit;
std::string sampleTime;
}ModelItem;
typedef QList<ModelItem> TableData;
class CWaitorCursor
{
public:
CWaitorCursor();
~CWaitorCursor();
};
//全局变量
class AppData:public Singleton<AppData>
{
public:
AppData(token);
~AppData();
AppData(const AppData &other) = delete;
AppData& operator=(const AppData &other) = delete;
public:
//数据表格的表头
QStringList lstDataTableHeaderText;
//定时刷新间隔
int nTimeOut;
//目标机器IP
QString qsDestinationIp;
//最后的错误信息
QString qsLastErrorString;
};
//全局通用类
class AppCommon:public Singleton<AppCommon>
{
public:
AppCommon(token);
~AppCommon();
AppCommon(const AppCommon&)=delete;
AppCommon& operator =(const AppCommon&)= delete;
public:
void InitializeTableView(MyTableModel* model,QTableView* tableView);
};
#endif // GLOBALPARAMETERS_H

View File

@ -66,6 +66,7 @@ int main(int argc, char *argv[])
w.move((scr_w - w.width()) / 2, (scr_h - w.height()) / 2);
w.show();
int ret = app.exec();
hlogi("=========--- I'll be back! ---=========");
return ret;

View File

@ -14,6 +14,8 @@
#include <QTableView>
#include <QStandardItemModel>
#include "devicepropertypage.h"
MainDialog::MainDialog(QWidget *parent) :
QMainWindow (parent),
ui(new Ui::MainDialog)
@ -22,12 +24,12 @@ MainDialog::MainDialog(QWidget *parent) :
this->setWindowIcon(QIcon(":/images/icon.png"));
InitializeUI();
//InitializeUI();
connect(m_pDeviceListWidget, &QListWidget::currentItemChanged, this, &MainDialog::changePage);
//
// Load the window state
loadWindowState();
//loadWindowState();
}
MainDialog::~MainDialog()
@ -96,6 +98,8 @@ void MainDialog::InitializeUI()
//resize(800, 600);
setMinimumSize(1024, 768);
connect(m_pDeviceListWidget, &QListWidget::currentItemChanged, this, &MainDialog::changePage);
}
@ -126,39 +130,22 @@ void MainDialog::CreateTablePage()
{
m_pDevicestackedWidget = new QStackedWidget(this);
QVBoxLayout *stackedWidgetLayout = new QVBoxLayout;
QVBoxLayout *stackedWidgetLayout = new QVBoxLayout();
m_pDevicestackedWidget->setLayout(stackedWidgetLayout);
// Create and set up QTableView
QTableView *tableView = new QTableView(this);
DevicePropertyPage *page1 = new DevicePropertyPage(m_pDevicestackedWidget);
DevicePropertyPage *page2 = new DevicePropertyPage(m_pDevicestackedWidget);
// Create and set up a model for the table view
QStandardItemModel *model = new QStandardItemModel(4, 3, this); // 4 rows, 3 columns
model->setHorizontalHeaderLabels(QStringList() << "Column 1" << "Column 2" << "Column 3");
m_pDevicestackedWidget->addWidget(page1); // Add QTableView as a page
m_pDevicestackedWidget->addWidget(page2);
// Fill the model with data
for (int row = 0; row < 4; ++row)
{
for (int col = 0; col < 3; ++col)
{
QStandardItem *item = new QStandardItem(QString("Item %1-%2").arg(row).arg(col));
model->setItem(row, col, item);
}
}
tableView->setModel(model);
m_pDevicestackedWidget->addWidget(tableView); // Add QTableView as a page
m_pDevicestackedWidget->addWidget(new QPushButton("Page 2"));
m_pDevicestackedWidget->addWidget(new QPushButton("Page 3"));
m_pDevicestackedWidget->addWidget(new QPushButton("Page 4"));
m_pDevicestackedWidget->addWidget(new QPushButton("Page 5"));
m_pDevicestackedWidget->addWidget(new QPushButton("Page 6"));
page1->InitializeTable();
page2->InitializeTable();
}
void MainDialog::CreateIcon(const QIcon& icon,QString text)

View File

@ -21,6 +21,9 @@ public:
explicit MainDialog(QWidget *parent = nullptr);
~MainDialog();
void InitializeUI();
void loadWindowState();
public slots:
void changePage(QListWidgetItem *current, QListWidgetItem *previous);
@ -37,7 +40,7 @@ private:
QToolBar *m_pMainToolBar;
private:
void InitializeUI();
void CreateToolbar();
void CreateIcon(const QIcon& icon,QString text);
void CreateTablePage();
@ -45,7 +48,6 @@ private:
protected:
void closeEvent(QCloseEvent *event) override;
void saveWindowState();
void loadWindowState();
};
#endif // MAINDIALOG_H

View File

@ -47,6 +47,8 @@ void MainWindow::setIp(const QString &ip)
void MainWindow::on_pb_Logon_clicked()
{
m_pMainDialog = new MainDialog();
m_pMainDialog->InitializeUI();
m_pMainDialog->loadWindowState();
m_pMainDialog->show();
this->close();
}

View File

@ -0,0 +1,140 @@
#include <QColor>
#include "mytablemodel.h"
MyTableModel::MyTableModel(QObject* parent)
:QAbstractTableModel(parent)
{
}
int MyTableModel::rowCount(const QModelIndex & /*parent*/) const
{
return m_modelData.size();
}
int MyTableModel::columnCount(const QModelIndex & /*parent*/) const
{
return AppData::getInstance()->lstDataTableHeaderText.count();
}
QVariant MyTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
const int row = index.row();
switch (index.column())
{
case 0:
{
if (m_modelData.at(row).status == STATUS_NORMAL) return tr("Normal");
if (m_modelData.at(row).status == STATUS_INFO) return tr("INFO");
if (m_modelData.at(row).status == STATUS_WARN) return tr("WARN");
if (m_modelData.at(row).status == STATUS_ERROR) return tr("ERROR");
}
case 1:
{
return m_modelData.at(row).ParameterName.c_str();
}
case 2: return m_modelData.at(row).value.c_str();
case 3: return m_modelData.at(row).unit.c_str();
case 4: return m_modelData.at(row).sampleTime.c_str();
}
}
//对齐处理
if (role == Qt::TextAlignmentRole)
{
//const int row = index.row();
switch (index.column())
{
case 2:
case 3:
return QVariant(Qt::AlignLeft|Qt::AlignVCenter);
break;
case 4:
return QVariant(Qt::AlignRight|Qt::AlignVCenter);
break;
default:
return Qt::AlignCenter;
break;
}
}
if (role == Qt::BackgroundRole)
{
const int row = index.row();
switch (index.column())
{
case 0: //状态
case 2: //数值
{
if (m_modelData.at(row).status == STATUS_WARN)
return QVariant(QColor(Qt::yellow));
else if (m_modelData.at(row).status == STATUS_ERROR)
return QVariant(QColor(Qt::red));
}
}
}
return QVariant();
}
QVariant MyTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
{
if (section < m_headeList.size())
{
return m_headeList[section];
}
}
return QAbstractItemModel::headerData(section, orientation, role);
}
const TableData *MyTableModel::getModelData() const
{
return &m_modelData;
}
bool MyTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
//beginResetModel();
if (!index.isValid())
return false;
//endResetModel(); //在结束前添加此函数
return QAbstractTableModel::setData(index, value, role);
}
Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const
{
return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
}
void MyTableModel::setModelData(TableData data)
{
//修改数据前后用beginResetModel()和endResetModel()
beginResetModel(); //通过这个告诉我要开始修改model了
m_modelData.clear();
for (int i = 0;i < data.count();++i)
{
m_modelData.append(data[i]);
}
endResetModel(); //通过这个告诉我修改model结束了
}
void MyTableModel::clearModelData()
{
m_modelData.clear();
}
void MyTableModel::setHeadData(QStringList i_list)
{
m_headeList=i_list;
}

View File

@ -0,0 +1,37 @@
#pragma execution_character_set("utf-8")
#ifndef MYTABLEMODEL_H
#define MYTABLEMODEL_H
#include <QAbstractTableModel>
#include <QString>
#include "globalparameters.h"
class MyTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
MyTableModel(QObject* parent);
int rowCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
int columnCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) Q_DECL_OVERRIDE;
Qt::ItemFlags flags(const QModelIndex& index) const Q_DECL_OVERRIDE;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
const TableData *getModelData() const;
private:
TableData m_modelData;
QStringList m_headeList;
public:
void setHeadData(QStringList i_list);
void setModelData(TableData data);
void clearModelData();
};
#endif // MYTABLEMODEL_H

View File

@ -0,0 +1,24 @@
#ifndef SINGLETON_H
#define SINGLETON_H
#include <iostream>
template<typename T>
class Singleton
{
public:
static T* getInstance() noexcept(std::is_nothrow_constructible<T>::value)
{
static T instance{token()};
return &instance;
}
virtual ~Singleton() =default;
Singleton(const Singleton&)=delete;
Singleton& operator =(const Singleton&)=delete;
protected:
struct token{}; // helper class
Singleton() noexcept=default;
};
#endif // SINGLETON_H