na razie z QAbstractItemModel
dałem sobie na luz, bo muszę przećwiczyć kila rzeczy... ale mam pytanie odnośnie innego obiektu QTableWidget
Czy w tym kodzie dodawanie i usuwanie wierszy jest wystarczająco dobrze napisane ? Czy dałoby się to ulepszyć lub coś zmienić/poprawić ?
poniżej cały kod
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QTableWidget>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
QWidget *mWidget;
QVBoxLayout *mLayout;
QHBoxLayout *pbLayoutTable;
QHBoxLayout *pbLayoutMain;
QTableWidget *tableWidg;
QPushButton *pbOpenFile, *pbSaveFile, *pbQuit, *pbAddRow, *pbRemoveRow;
private slots:
void myAddRow();
void myRemRow();
signals:
void myRow(int);
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
resize(600, 370);
mWidget = new QWidget(this); //![1]
mLayout = new QVBoxLayout(mWidget); //![2]
pbLayoutTable = new QHBoxLayout(); //![3]
pbLayoutMain = new QHBoxLayout(); //![4]
pbOpenFile = new QPushButton(mWidget);
pbOpenFile->setText("Open CSV file");
pbSaveFile = new QPushButton(mWidget);
pbSaveFile->setText("Save as CSV file");
pbQuit = new QPushButton(mWidget);
pbQuit->setText("Quit");
pbAddRow = new QPushButton(mWidget);
pbAddRow->setText("Add row");
pbRemoveRow = new QPushButton(mWidget);
pbRemoveRow->setText("Remove row");
tableWidg = new QTableWidget();
mWidget->setLayout(mLayout);
pbLayoutTable->addWidget(pbAddRow);
pbLayoutTable->addWidget(pbRemoveRow);
pbLayoutMain->addWidget(pbOpenFile);
pbLayoutMain->addWidget(pbSaveFile);
pbLayoutMain->addWidget(pbQuit);
mLayout->addWidget(tableWidg);
mLayout->addLayout(pbLayoutTable);
mLayout->addLayout(pbLayoutMain);
QObject::connect(pbQuit, &QPushButton::clicked, this, &MainWindow::close);
QObject::connect(pbAddRow, &QPushButton::clicked, this, &MainWindow::myAddRow);
QObject::connect(this, &MainWindow::myRow, tableWidg, &QTableWidget::insertRow);
QObject::connect(pbRemoveRow, &QPushButton::clicked, this, &MainWindow::myRemRow);
setCentralWidget(mWidget);
}
void MainWindow::myAddRow()
{
int myRowCnt;
myRowCnt = tableWidg->rowCount();
if(myRowCnt == 0){
emit myRow(myRowCnt);
for(int i=0; i<5; ++i){
tableWidg->insertColumn(i);
}
}
else{
emit myRow(myRowCnt);
}
}
void MainWindow::myRemRow()
{
tableWidg->removeRow(tableWidg->currentRow());
}
MainWindow::~MainWindow()
{
delete pbRemoveRow;
delete pbAddRow;
delete pbQuit;
delete pbSaveFile;
delete pbOpenFile;
delete pbLayoutMain; //![4]
delete pbLayoutTable; //![3]
delete mLayout; //![2]
delete mWidget; //![1]
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}