Qt初始化QTableView并显示右键菜单

初始化QTableView

经常在窗体上需要按要求显示若干个表格并初始化后,以及右键菜单功能;

下面给出实例代码,不能直接运行,因为缺少相应变量,仅供参考;

首先在变量layout要清空,再创建新layout;

然后创建QTableView、QStandardItemModel;

Model设置大小和Item字体等;

QTableView设置成Model;

添加QTableView,vlayout->addWidget(tableVec[i]);

完成vlayout后QWidget设置vlayout;

//初始化tableview 以便输入编号
void MainWindow::initTableView()
{
    if(vlayout)
    {
        QLayoutItem *child;
        while ((child = vlayout->takeAt(0)) != nullptr) {
            if(child->widget())
                delete child->widget();
            delete child;
        }
    }
    vlayout = new QVBoxLayout;
    int size = map.size();
    qDebug() << "map size = " << size << endl;
    tableVec.clear();
    modelVec.clear();
    tableVec.resize(size);
    modelVec.resize(size);
    QMap>::iterator it = map.begin();
    QFont font12 = QFont("SimHei",12);
    QFont font10 = QFont("SimHei",10);
    for(int i = 0; i < size; i++)
    {
      //qDebug() << "i = " << i << endl;
      tableVec[i] = new QTableView;
      modelVec[i] = new QStandardItemModel;
      modelVec[i]->setColumnCount(14);
      QStringList colHeader;
      colHeader << tr("Frame") << tr("Tier");
      for(int j = 0; j < 12; j++)
      {
          colHeader << QString("%1 A/B").arg(j+1);
      }
      modelVec[i]->setHorizontalHeaderLabels(colHeader);
      modelVec[i]->setRowCount(it.value().size()*2);
      QStandardItem * item = new QStandardItem(QString(tr("Frame%1")).arg(it.key()));
      item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
      item->setFont(font12);
      item->setEditable(false);
      modelVec[i]->setItem(0,0,item);

      //有多少层 需要测试
      for(int j = 0; j < it.value().size(); j++)
      {

          int TierNo = monitorList[it.value()[j]][1], addr = monitorList[it.value()[j]][2];
          qDebug() << "Frame " << it.key() << " Tier " << TierNo << " addr = " << addr;
          QStandardItem * item1 = new QStandardItem(QString(tr("Tier%1-Addr%2")).arg(TierNo).arg(addr,2,16,QLatin1Char('0')));
          item1->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
          item1->setFont(font10);
          item1->setEditable(false);
          modelVec[i]->setItem(2*j,1,item1);
          for(int k = 2; k < 14; k++)
          {
              QStandardItem * item2 = new QStandardItem(QString(""));
              item2->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
              item2->setFont(font10);
              modelVec[i]->setItem(2*j,k,item2);
          }
          for(int k = 2; k < 14; k++)
          {
              QStandardItem * item3 = new QStandardItem(QString(""));
              item3->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
              item3->setFont(font10);
              modelVec[i]->setItem(2*j+1,k,item3);
          }

      }
      tableVec[i]->setModel(modelVec[i]);
      tableVec[i]->setSpan(0,0,it.value().size()*2,1);
      for(int j = 0; j < it.value().size(); j++)
      {
        tableVec[i]->setSpan(2*j,1,2,1);
      }
      tableVec[i]->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
      tableVec[i]->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
      //添加右键菜单
      tableVec[i]->setContextMenuPolicy(Qt::CustomContextMenu);
      connect(tableVec[i],SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(Menu_Slot(QPoint)));
      vlayout->addWidget(tableVec[i]);
      it++;
    }
    delete ui->tabWidget->widget(0)->layout();
    ui->tabWidget->widget(0)->setLayout(vlayout);
}

右键菜单

tableVec[i]->setContextMenuPolicy(Qt::CustomContextMenu);

绑定槽函数Menu_Slot(QPoint);

showLine->setParent(curr_tableview);这样action就可以找到对象TableView了;

void MainWindow::Menu_Slot(QPoint p)
{
    auto curr_tableview = qobject_cast(sender());
    QModelIndex index = curr_tableview->indexAt(p);
    if(index.isValid())
    {
        QItemSelectionModel* selections = curr_tableview->selectionModel();//获取当前的选择模型
        QModelIndexList selected = selections->selectedIndexes();//返回当前选择的模型索引
        if(selected.count() == 1)
        {
            showLine->setParent(curr_tableview);
            showLine->setVisible(true);
            tableviewMenu->exec(QCursor::pos());
            qDebug() << "index " << index << " is chosen!";
        }

    }
}

响应动作函数 用于显示曲线

void MainWindow::showModuleLine()
{

    //获取表格和对象
    auto curr_tableview = qobject_cast((qobject_cast(sender()))->parent());
    int tableIndex = -1;
    //取得tableview索引
    if(ui->tabWidget->currentIndex()==0)
    {
        for(int i = 0; i < tableVec.size(); i++)
        {
            if(curr_tableview == tableVec[i])
            {
                tableIndex = i;
                break;
            }
        }
    }
    else
        return;
    qDebug() << "show ModuleLine triggered! table index: " << tableIndex ;
    if(tableIndex==-1) return;
    QModelIndex index = curr_tableview->currentIndex();
    QString module;
    if(index.isValid() && index.column() >= 2 && index.column() < 14)
    {
        int row = index.row(), col = index.column();
        module = tableVec[tableIndex]->model()->data(tableVec[tableIndex]->model()->index(row,col),Qt::DisplayRole).toString();
        qDebug() << module ;
        if(module == "") return;
    }
    else
        return;
    //module不为空 显示曲线
    ui->tabWidget->setCurrentIndex(2);
    //从数据库取得所有数据
    QList line = m_order->getDataPoints(module);
    if(line.size() <= 0) return;
    chart->removeAllSeries();
    axisX->setRange(QDateTime::fromMSecsSinceEpoch(line.front().x()),QDateTime::fromMSecsSinceEpoch(line.back().x()));

    series = new QLineSeries();
    series->append(line);
    series->setName("1");//曲线添加名称
    chart->addSeries(series);
    series->attachAxis(axisY);
    series->attachAxis(axisX);
    connect(series, &QLineSeries::hovered, this, &MainWindow::tooltip);
    ui->graphicsView->setChart(chart);
    chart->zoom(0.9999);
    chart->setFocus();
    chart->setTitle(tr("历史数据-")+module);
    qDebug() <<  "show module records success!";
    statusBar()->showMessage(tr("显示模块数据成功!"), 5000);
}

mainwindow.cpp中初始化

#include "mainwindow.h"

#include 
#include 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include 
#include "callout.h"

#include 

#include 
#include 
#include "chartview.h"
#include "chart.h"

QT_CHARTS_USE_NAMESPACE


#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    vlayout(nullptr),
    vlayout2(nullptr),
    m_tooltip(nullptr)
{
    ui->setupUi(this);

    
    tableviewMenu = new QMenu();
    showLine = new QAction("显示曲线");
    tableviewMenu->addAction(showLine);
    connect(showLine,SIGNAL(triggered()),this,SLOT(showModuleLine()));
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 

#include "chart.h"
#include "chartview.h"

#include 
#include 
#include 
#include 
#include 
#include 
#include 

QT_BEGIN_NAMESPACE
class QModbusClient;
namespace Ui {
class MainWindow;
}

QT_END_NAMESPACE

class Callout;

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    void setAdmin();
    void setUserName(QString usr);
private:
    Ui::MainWindow *ui;

    //QChart * chart;
    Chart *chart;
    QLineSeries * series;

    QDateTimeAxis *axisX;
    QValueAxis *axisY;
    const QString DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

    QList> monitorList;//FrameNo, TierNo, Addr
    QList> moduleList;//moduleID

    QList addrList;//address list 便于查询对应数据并更新
    QMap> map;//架号和Vector绑定 记录在monitorList中的索引
    QVBoxLayout *vlayout, *vlayout2;
    QVector tableVec,tableVec2;
    QVector modelVec,modelVec2;

    Callout *m_tooltip;

    //menu
    QMenu * tableviewMenu;
    QAction * showLine;

    void initTableView();
    
private slots:
    void showModuleLine();
    void Menu_Slot(QPoint p);
};

#endif // MAINWINDOW_H

你可能感兴趣的:(Qt,qt,开发语言,c++)