QT中自定义代理

自定义代理的基本设计要求

image

QAbstractItemDelegate是所有代理类的抽象基类;
QStyledItemDelegate是视图组件使用的缺省的代理类,QItemDelegate也是类似功能的类。
QStyledItemDelegate 与 QItemDelegate的差别在于:QStyledItemDelegate可以使用当前的样式表设置来绘制组件,建议使用QStyledItemDelegate作为自定义代理组件的基类。
QStyledItemDelegate 或者是 QItemDelegate继承设计自定义代理组件,都必须实现4个函数:

  • createEditor()函数:创建用于编辑模型数据的widget组件,如一个QSpinBox组件,或一个QComboBox组件;
  • setEditorData():函数从数据模型获取数据,供 widget组件进行编辑;
  • setModelData():将 widget上的数据更新到数据模型;
  • updateEditorGeometry():用于给widget组件设置一个合适的大小。

整体代码

MyIntSpinBoxDelegate代码实现

MyIntSpinBoxDelegate.h

#pragma once
#include <QStyledItemDelegate>
class MyIntSpinBoxDelegate :public QStyledItemDelegate
{
	Q_OBJECT
public:
	MyIntSpinBoxDelegate(QObject* parent = nullptr);
	//自定义代理组件必须继承以下4个函数
	QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const Q_DECL_OVERRIDE;
	void setEditorData(QWidget* editor, const QModelIndex& index) const Q_DECL_OVERRIDE;
	void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const Q_DECL_OVERRIDE;
	void updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const Q_DECL_OVERRIDE;
};

MyIntSpinBoxDelegate.cpp

#include "MyIntSpinBoxDelegate.h"
#include <QSpinBox>

MyIntSpinBoxDelegate::MyIntSpinBoxDelegate(QObject* parent) :QStyledItemDelegate(parent)
{
}
/*
createEditor()函数用于创建需要的编辑组件.
*/
QWidget* MyIntSpinBoxDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	//创建代理编辑组件
	QSpinBox* editor = new QSpinBox(parent);//创建一个QSpinBox类型的编辑器editor,parent指向视图组件,然后对创建的editor做一些设置
	editor->setFrame(false);//设置为无边框
	editor->setMinimum(0);
	editor->setMaximum(10000);
	return editor;//返回此编辑器
}
/*
setEditorData()函数用于从数据模型获取值,设置为编辑器的显示值。
当双击一个单元格进入编辑状态时,就会自动调用此函数
*/
void MyIntSpinBoxDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
	//从数据模型获取数据,显示到代理组件中
	int value = index.model()->data(index, Qt::EditRole).toInt();
	QSpinBox* spinBox = static_cast<QSpinBox*>(editor);
	spinBox->setValue(value);
}

/*
setModelData()函数用于将代理编辑器上的值更新给数据模型,
当用户在界面上完成编辑时会自动调用此函数,将界面上的数据更新到数据模型
*/
void MyIntSpinBoxDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
  //将代理组件的数据保存到数据模型中
	QSpinBox* spinBox= static_cast<QSpinBox*>(editor);
	spinBox->interpretText();
	int value = spinBox->value();
	model->setData(index, value, Qt::EditRole);
}
void MyIntSpinBoxDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	editor->setGeometry(option.rect);
}

MyDoubleSpinBoxDelegate代码实现

MyDoubleSpinBoxDelegate.h

#pragma once
#include    <QObject>
#include    <QWidget>
#include    <QStyledItemDelegate>
class MyDoubleSpinBoxDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    MyDoubleSpinBoxDelegate(QObject* parent = 0);
    //自定义代理组件必须继承以下4个函数
    //创建编辑组件
    QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option,
        const QModelIndex& index) const Q_DECL_OVERRIDE;
    void setEditorData(QWidget* editor, const QModelIndex& index) const Q_DECL_OVERRIDE;
    void setModelData(QWidget* editor, QAbstractItemModel* model,
        const QModelIndex& index) const Q_DECL_OVERRIDE;
    void updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option,
        const QModelIndex& index) const Q_DECL_OVERRIDE;
};

MyDoubleSpinBoxDelegate.cpp

#include "MyDoubleSpinBoxDelegate.h"
#include  <QDoubleSpinBox>

MyDoubleSpinBoxDelegate::MyDoubleSpinBoxDelegate(QObject* parent) :QStyledItemDelegate(parent)
{    
}

QWidget* MyDoubleSpinBoxDelegate::createEditor(QWidget* parent,
    const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);

    QDoubleSpinBox* editor = new QDoubleSpinBox(parent);
    editor->setFrame(false);
    editor->setMinimum(0);
    editor->setDecimals(2);
    editor->setMaximum(10000);
    return editor;
}

void MyDoubleSpinBoxDelegate::setEditorData(QWidget* editor,
    const QModelIndex& index) const
{
    float value = index.model()->data(index, Qt::EditRole).toFloat();
    QDoubleSpinBox* spinBox = static_cast<QDoubleSpinBox*>(editor);
    spinBox->setValue(value);
}

void MyDoubleSpinBoxDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    QDoubleSpinBox* spinBox = static_cast<QDoubleSpinBox*>(editor);
    spinBox->interpretText();
    float value = spinBox->value();
    QString str = QString::asprintf("%.2f", value);

    model->setData(index, str, Qt::EditRole);
}

void MyDoubleSpinBoxDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    editor->setGeometry(option.rect);
}

MyComboboxDelegate代码实现

MyComboboxDelegate.h

#pragma once
#include    <QItemDelegate>
class MyComboboxDelegate : public QItemDelegate
{
    Q_OBJECT
public:
    MyComboboxDelegate(QObject* parent = 0);

    //自定义代理组件必须继承以下4个函数
    QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option,
        const QModelIndex& index) const Q_DECL_OVERRIDE;

    void setEditorData(QWidget* editor, const QModelIndex& index) const Q_DECL_OVERRIDE;
    void setModelData(QWidget* editor, QAbstractItemModel* model,
        const QModelIndex& index) const Q_DECL_OVERRIDE;
    void updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option,
        const QModelIndex& index) const Q_DECL_OVERRIDE;
};

MyComboboxDelegate.cpp

#include "MyComboboxDelegate.h"
#include    <QComboBox>

MyComboboxDelegate::MyComboboxDelegate(QObject* parent) :QItemDelegate(parent)
{
}

QWidget* MyComboboxDelegate::createEditor(QWidget* parent,
    const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QComboBox* editor = new QComboBox(parent);

    editor->addItem(QStringLiteral("优"));
    editor->addItem(QStringLiteral("良"));
    editor->addItem(QStringLiteral("一般"));
    editor->addItem(QStringLiteral("不合格"));

    return editor;
}

void MyComboboxDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
    QString str = index.model()->data(index, Qt::EditRole).toString();

    QComboBox* comboBox = static_cast<QComboBox*>(editor);
    comboBox->setCurrentText(str);
}

void MyComboboxDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    QComboBox* comboBox = static_cast<QComboBox*>(editor);

    QString str = comboBox->currentText();

    model->setData(index, str, Qt::EditRole);
}

void MyComboboxDelegate::updateEditorGeometry(QWidget* editor,
    const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    editor->setGeometry(option.rect);
}

MainWindow的实现

MainWindow.h

#pragma once
#include <QLabel>
#include <QtWidgets/QMainWindow>
#include  <QStandardItemModel>
#include <QItemSelectionModel>
#include <QTableView>
#include <QPlainTextEdit>
#include <QAction>
#include <QToolbar>
#include "MyIntSpinBoxDelegate.h"
#include "MyDoubleSpinBoxDelegate.h"
#include "MyComboboxDelegate.h"
#define     FixedColumnCount    6       //文件固定6行
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:

    //用于状态栏的信息显示
    QLabel* LabCurFile;  //当前文件
    QLabel* LabCellPos;    //当前单元格行列号
    QLabel* LabCellText;   //当前单元格内容
    MyIntSpinBoxDelegate    intSpinDelegate; //整型数
    MyDoubleSpinBoxDelegate doubleSpinDelegate; //浮点数
    MyComboboxDelegate   comboBoxDelegate; //列表选择
    QString fCurFile;//当前文件名
    QStandardItemModel* m_theModel;//数据模型
    QItemSelectionModel* m_theSelection;//Item选择模型
    void    iniModelFromStringList(QStringList&);//从StringList初始化数据模型
    QTableView* m_tableView;
    QPlainTextEdit* m_plainTextEdit;
    QToolBar* m_mainToolBar;
    QAction* actOpen;
    QAction* actSave;
    QAction* actAppend;
    QAction* actInsert;
    QAction* actDelete;
    QAction* actExit;
    QAction* actModelData;
    QAction* actAlignLeft;
    QAction* actAlignCenter;
    QAction* actAlignRight;
    QAction* actFontBold;

private slots:
    void on_currentChanged(const QModelIndex& current, const QModelIndex& previous);
    void on_actOpen_triggered(); //打开文件
    void on_actAppend_triggered(); //添加行
    void on_actInsert_triggered();//插入行
    void on_actDelete_triggered();//删除行
    void on_actModelData_triggered();  //到处模型数据
    void on_actSave_triggered();//保存文件
    void on_actAlignCenter_triggered();
    void on_actFontBold_triggered(bool checked);
    void on_actAlignLeft_triggered();
    void on_actAlignRight_triggered();   
   

};

MainWindow.cpp

#include "MainWindow.h"
#include <QApplication>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
#include <QStatusBar>
#include <QSplitter>
#include <QIcon>
#include <QWidget>


MainWindow::MainWindow(QWidget *parent): QMainWindow(parent)
{
    //Splitter控件
    QSplitter* splitter = new QSplitter(this);
    setCentralWidget(splitter); //指定为中心控件
    splitter->setOrientation(Qt::Horizontal);//设置分割方向
    //创建TableView
    this->m_tableView = new QTableView(this);
    splitter->addWidget(m_tableView);//加入Splitter控件中

    //创建QPlainTextEdit
    this->m_plainTextEdit = new QPlainTextEdit(this);    
    splitter->addWidget(m_plainTextEdit);//加入Splitter控件中

    m_theModel = new QStandardItemModel(2, FixedColumnCount, this); //创建数据模型
    m_theSelection = new QItemSelectionModel(m_theModel);//Item选择模型
    connect(m_theSelection, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
        this, SLOT(on_currentChanged(QModelIndex, QModelIndex)));

    //为tableView设置数据模型
    this->m_tableView->setModel(m_theModel); //设置数据模型
   this->m_tableView->setSelectionModel(m_theSelection);//设置选择模型

    //为各列设置自定义代理组件
     this->m_tableView->setItemDelegateForColumn(0, &intSpinDelegate);  //测深,整数
     this->m_tableView->setItemDelegateForColumn(1, &doubleSpinDelegate);  //浮点数
     this->m_tableView->setItemDelegateForColumn(2, &doubleSpinDelegate); //浮点数
     this->m_tableView->setItemDelegateForColumn(3, &doubleSpinDelegate); //浮点数
     this->m_tableView->setItemDelegateForColumn(4, &comboBoxDelegate); //Combbox选择型    

    //创建状态栏组件
    LabCurFile = new QLabel(QStringLiteral("当前文件:"), this);
    LabCurFile->setMinimumWidth(300);
    LabCellPos = new QLabel(QStringLiteral(" 当前单元格:"), this);
    LabCellPos->setMinimumWidth(180);
    LabCellPos->setAlignment(Qt::AlignHCenter);
    LabCellText = new QLabel(QStringLiteral(" 单元格内容:"), this);
    LabCellText->setMinimumWidth(200);
    this->statusBar()->addWidget(LabCurFile);
    this->statusBar()->addWidget(LabCellPos);
    this->statusBar()->addWidget(LabCellText);
    
    //初始化Action
    actOpen = new QAction(this);
    actOpen->setObjectName(QStringLiteral("actOpen"));
    QIcon icon;
    icon.addFile(QStringLiteral(":/images/icons/open.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actOpen->setIcon(icon);
    actSave = new QAction(this);
    actSave->setObjectName(QStringLiteral("actSave"));
    actSave->setEnabled(false);
    QIcon icon1;
    icon1.addFile(QStringLiteral(":/images/icons/save.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actSave->setIcon(icon1);
    actAppend = new QAction(this);
    actAppend->setObjectName(QStringLiteral("actAppend"));
    actAppend->setEnabled(false);
    QIcon icon2;
    icon2.addFile(QStringLiteral(":/images/icons/append.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actAppend->setIcon(icon2);
    actInsert = new QAction(this);
    actInsert->setObjectName(QStringLiteral("actInsert"));
    actInsert->setEnabled(false);
    QIcon icon3;
    icon3.addFile(QStringLiteral(":/images/icons/306.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actInsert->setIcon(icon3);
    actDelete = new QAction(this);
    actDelete->setObjectName(QStringLiteral("actDelete"));
    actDelete->setEnabled(false);
    QIcon icon4;
    icon4.addFile(QStringLiteral(":/images/icons/delete.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actDelete->setIcon(icon4);
    actExit = new QAction(this);
    actExit->setObjectName(QStringLiteral("actExit"));
    QIcon icon5;
    icon5.addFile(QStringLiteral(":/images/icons/exit.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actExit->setIcon(icon5);
    actModelData = new QAction(this);
    actModelData->setObjectName(QStringLiteral("actModelData"));
    QIcon icon6;
    icon6.addFile(QStringLiteral(":/images/icons/import1.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actModelData->setIcon(icon6);
    actAlignLeft = new QAction(this);
    actAlignLeft->setObjectName(QStringLiteral("actAlignLeft"));
    QIcon icon7;
    icon7.addFile(QStringLiteral(":/images/icons/508.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actAlignLeft->setIcon(icon7);
    actAlignCenter = new QAction(this);
    actAlignCenter->setObjectName(QStringLiteral("actAlignCenter"));
    QIcon icon8;
    icon8.addFile(QStringLiteral(":/images/icons/510.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actAlignCenter->setIcon(icon8);
    actAlignRight = new QAction(this);
    actAlignRight->setObjectName(QStringLiteral("actAlignRight"));
    QIcon icon9;
    icon9.addFile(QStringLiteral(":/images/icons/512.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actAlignRight->setIcon(icon9);
    actFontBold = new QAction(this);
    actFontBold->setObjectName(QStringLiteral("actFontBold"));
    actFontBold->setCheckable(true);
    QIcon icon10;
    icon10.addFile(QStringLiteral(":/images/icons/500.bmp"), QSize(), QIcon::Normal, QIcon::Off);
    actFontBold->setIcon(icon10);
  
    //创建QToolBar
    m_mainToolBar = new QToolBar(this);
    m_mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
    m_mainToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    //将Toolbar加到主窗口的工具栏上
    this->addToolBar(Qt::TopToolBarArea, m_mainToolBar);
    //将Action加到ToolBar上
    m_mainToolBar->addAction(actOpen);
    m_mainToolBar->addAction(actSave);
    m_mainToolBar->addAction(actModelData);
    m_mainToolBar->addSeparator();
    m_mainToolBar->addAction(actAppend);
    m_mainToolBar->addAction(actInsert);
    m_mainToolBar->addAction(actDelete);
    m_mainToolBar->addSeparator();
    m_mainToolBar->addAction(actAlignLeft);
    m_mainToolBar->addAction(actAlignCenter);
    m_mainToolBar->addAction(actAlignRight);
    m_mainToolBar->addAction(actFontBold);
    m_mainToolBar->addSeparator();
    m_mainToolBar->addAction(actExit);
    //退出Action连接close槽
    QObject::connect(actExit, SIGNAL(triggered()), this, SLOT(close()));
    //根据名字槽的连接
    QMetaObject::connectSlotsByName(this);
}

MainWindow::~MainWindow()
{}

void MainWindow::iniModelFromStringList(QStringList& aFileContent)
{ //从一个StringList 获取数据,初始化Model
    int rowCnt = aFileContent.count(); // 第1行是标题头,
    m_theModel->setRowCount(rowCnt - 1); //数据行数

    QString header, aLineText;
    QStandardItem* aItem;
    QStringList     headerList, tmpList;

    //设置表头
    header = aFileContent.at(0);//第1行是表头
    headerList = header.split(QRegExp("\\s+"), QString::SkipEmptyParts);//一个或多个空格、TAB等分隔符隔开的字符串
    m_theModel->setHorizontalHeaderLabels(headerList); //设置表头文字

    //设置表格数据
    int i, j;
    for (i = 1;i < rowCnt;i++)
    {
        aLineText = aFileContent.at(i); //获取stringList的一行
        tmpList = aLineText.split(QRegExp("\\s+"), QString::SkipEmptyParts);//一个或多个空格、TAB等分隔符隔开的字符串分解为多个字符串
        for (j = 0;j < FixedColumnCount - 1;j++)
        {
            aItem = new QStandardItem(tmpList.at(j));//创建item
            m_theModel->setItem(i - 1, j, aItem); //为模型的某个行列位置设置Item
        }
        aItem = new QStandardItem(headerList.at(j));//最后一列是Checkable,设置
        aItem->setCheckable(true);
        if (tmpList.at(j) == "0")
            aItem->setCheckState(Qt::Unchecked);
        else
            aItem->setCheckState(Qt::Checked);
        m_theModel->setItem(i - 1, j, aItem); //为模型的某个行列位置设置Item
    }
}

void MainWindow::on_currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
    Q_UNUSED(previous);
    if (current.isValid())
    {
        LabCellPos->setText(QStringLiteral("当前单元格:%1行,%2列").arg(current.row()).arg(current.column()));
        QStandardItem* aItem;
        aItem = m_theModel->itemFromIndex(current); //从模型索引获得Item
        this->LabCellText->setText(QStringLiteral("单元格内容:%1").arg( aItem->text()));

        QFont   font = aItem->font();
        this->actFontBold->setChecked(font.bold());
    }
}

void MainWindow::on_actOpen_triggered()
{
    QString curPath, aFileName, str;
    curPath = QCoreApplication::applicationDirPath(); //获取应用程序的路径
    //调用打开文件对话框打开一个文件
    aFileName = QFileDialog::getOpenFileName(this, QStringLiteral("打开一个文件"), curPath,
        QStringLiteral("井斜数据文件(*.txt);;所有文件(*.*)"));

    if (aFileName.isEmpty())
        return; 

    QStringList fFileContent;
    QFile aFile(aFileName);  //以文件方式读出
    if (aFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream aStream(&aFile); //用文本流读取文件
        this->m_plainTextEdit->clear();
        while (!aStream.atEnd())
        {
            str = aStream.readLine();//读取文件的一行
            this->m_plainTextEdit->appendPlainText(str); //添加到文本框显示
            fFileContent.append(str); //添加到StringList
        }
        aFile.close();

        this->LabCurFile->setText(QStringLiteral("当前文件:%1").arg(aFileName) );
        this->actAppend->setEnabled(true);
        this->actInsert->setEnabled(true);
        this->actDelete->setEnabled(true);
        this->actSave->setEnabled(true);

        iniModelFromStringList(fFileContent);//初始化数据模型
    }
}

void MainWindow::on_actAppend_triggered()
{ //添加行
    QList<QStandardItem*>    aItemList; //容器类
    QStandardItem* aItem;
    QString str;
    for (int i = 0;i < FixedColumnCount - 2;i++)
    {
        aItem = new QStandardItem("0"); //创建Item
        aItemList << aItem;   //添加到容器
    }
    aItem = new QStandardItem(QStringLiteral("优")); //创建Item
    aItemList << aItem;   //添加到容器

    str = m_theModel->headerData(m_theModel->columnCount() - 1, Qt::Horizontal, Qt::DisplayRole).toString();
    aItem = new QStandardItem(str); //创建Item
    aItem->setCheckable(true);
    aItemList << aItem;   //添加到容器

    m_theModel->insertRow(m_theModel->rowCount(), aItemList); //插入一行,需要每个Cell的Item
    QModelIndex curIndex = m_theModel->index(m_theModel->rowCount() - 1, 0);//创建最后一行的ModelIndex
    m_theSelection->clearSelection();
    m_theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
}

void MainWindow::on_actInsert_triggered()
{//插入行
    QList<QStandardItem*>    aItemList;  //QStandardItem的容器类
    QStandardItem* aItem;
    QString str;
    for (int i = 0;i < FixedColumnCount - 2;i++)
    {
        aItem = new QStandardItem("0"); //新建一个QStandardItem
        aItemList << aItem;//添加到容器类
    }
    aItem = new QStandardItem(QStringLiteral("优")); //新建一个QStandardItem
    aItemList << aItem;//添加到容器类

    str = m_theModel->headerData(m_theModel->columnCount() - 1, Qt::Horizontal, Qt::DisplayRole).toString();
    aItem = new QStandardItem(str); //创建Item
    aItem->setCheckable(true);
    aItemList << aItem;//添加到容器类
    QModelIndex curIndex = m_theSelection->currentIndex();
    m_theModel->insertRow(curIndex.row(), aItemList);
    m_theSelection->clearSelection();
    m_theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
}

void MainWindow::on_actDelete_triggered()
{ //删除行
    QModelIndex curIndex = m_theSelection->currentIndex();
    if (curIndex.row() == m_theModel->rowCount() - 1)//(curIndex.isValid())
        m_theModel->removeRow(curIndex.row());
    else
    {
        m_theModel->removeRow(curIndex.row());
        m_theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
    }
}

void MainWindow::on_actModelData_triggered()
{//模型数据导出到PlainTextEdit显示
    this->m_plainTextEdit->clear(); //清空
    QStandardItem* aItem;
    QString str;

    //获取表头文字
    int i, j;
    for (i = 0;i < m_theModel->columnCount();i++)
    { //
        aItem = m_theModel->horizontalHeaderItem(i); //表头
        str = str + aItem->text() + "\t";
    }
    this->m_plainTextEdit->appendPlainText(str);


    //获取数据区的每行
    for (i = 0;i < m_theModel->rowCount();i++)
    {
        str = "";
        for (j = 0;j < m_theModel->columnCount() - 1;j++)
        {
            aItem = m_theModel->item(i, j);
            str = str + aItem->text() + QString::asprintf("\t"); //以 TAB分隔
        }
        aItem = m_theModel->item(i, j);
        if (aItem->checkState() == Qt::Checked)
            str = str + "1";
        else
            str = str + "0";


        this->m_plainTextEdit->appendPlainText(str);
    }

}

void MainWindow::on_actSave_triggered()
{ //保存为文件
    QString curPath, aFileName;
    curPath = QCoreApplication::applicationDirPath(); //获取应用程序的路径
    //调用打开文件对话框选择一个文件
    aFileName = QFileDialog::getSaveFileName(this, QStringLiteral("选择一个文件"), curPath,
        QStringLiteral("井斜数据文件(*.txt);;所有文件(*.*)"));

    if (aFileName.isEmpty())
        return; //

    QFile aFile(aFileName);  //以文件方式读出
    if (!(aFile.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate)))
        return;

    QTextStream aStream(&aFile); //用文本流读取文件

    QStandardItem* aItem;
    int i, j;
    QString str;

    this->m_plainTextEdit->clear();

    //获取表头文字
    for (i = 0;i < m_theModel->columnCount();i++)
    {
        aItem = m_theModel->horizontalHeaderItem(i);
        str = str + aItem->text() + "\t\t";
    }
    aStream << str << "\n";  //文件里需要加入 \n
    this->m_plainTextEdit->appendPlainText(str);

    //获取数据区文字,
    for (i = 0;i < m_theModel->rowCount();i++)
    {
        str = "";
        for (j = 0;j < m_theModel->columnCount() - 1;j++)
        {
            aItem = m_theModel->item(i, j);
            str = str + aItem->text() + QString::asprintf("\t\t");
        }

        aItem = m_theModel->item(i, j);
        if (aItem->checkState() == Qt::Checked)
            str = str + "1";
        else
            str = str + "0";

        this->m_plainTextEdit->appendPlainText(str);
        aStream << str << "\n";
    }
}

void MainWindow::on_actAlignCenter_triggered()
{
    if (!m_theSelection->hasSelection())
        return;

    QModelIndexList selectedIndix = m_theSelection->selectedIndexes();

    QModelIndex aIndex;
    QStandardItem* aItem;

    for (int i = 0;i < selectedIndix.count();i++)
    {
        aIndex = selectedIndix.at(i);
        aItem = m_theModel->itemFromIndex(aIndex);
        aItem->setTextAlignment(Qt::AlignHCenter);
    }
}

void MainWindow::on_actFontBold_triggered(bool checked)
{
    if (!m_theSelection->hasSelection())
        return;

    QModelIndexList selectedIndix = m_theSelection->selectedIndexes();

    QModelIndex aIndex;
    QStandardItem* aItem;
    QFont   font;

    for (int i = 0;i < selectedIndix.count();i++)
    {
        aIndex = selectedIndix.at(i);
        aItem = m_theModel->itemFromIndex(aIndex);
        font = aItem->font();
        font.setBold(checked);
        aItem->setFont(font);
    }

}

void MainWindow::on_actAlignLeft_triggered()
{
    if (!m_theSelection->hasSelection())
        return;

    QModelIndexList selectedIndix = m_theSelection->selectedIndexes();

    QModelIndex aIndex;
    QStandardItem* aItem;

    for (int i = 0;i < selectedIndix.count();i++)
    {
        aIndex = selectedIndix.at(i);
        aItem = m_theModel->itemFromIndex(aIndex);
        aItem->setTextAlignment(Qt::AlignLeft);
    }
}

void MainWindow::on_actAlignRight_triggered()
{
    if (!m_theSelection->hasSelection())
        return;

    QModelIndexList selectedIndix = m_theSelection->selectedIndexes();

    QModelIndex aIndex;
    QStandardItem* aItem;

    for (int i = 0;i < selectedIndix.count();i++)
    {
        aIndex = selectedIndix.at(i);
        aItem = m_theModel->itemFromIndex(aIndex);
        aItem->setTextAlignment(Qt::AlignRight);
    }
}

运行示例

image

代码下载地址

源代码

posted @ 2025-11-08 08:06  焦涛  阅读(24)  评论(0)    收藏  举报