Created
April 23, 2014 18:22
-
-
Save ulvham/11226982 to your computer and use it in GitHub Desktop.
workabstractitemmodel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "widget.h" | |
#include "ui_widget.h" | |
bool flag_exit=false; | |
DataBase db; | |
QSettings settings("base"); | |
QString path_db = settings.value("databasepathclosemonth").toString (); | |
QString query_db = "SELECT c.name, c.num_contract FROM contragents c ORDER BY c.name ASC"; | |
Widget::Widget(QWidget *parent) : | |
QWidget(parent), | |
ui(new Ui::Widget) | |
{ | |
ui->setupUi(this); | |
} | |
Widget::~Widget() | |
{ | |
delete ui; | |
} | |
ExampleItem::ExampleItem() | |
{ | |
this->date = ""; | |
this->time = ""; | |
this->text = ""; | |
} | |
void ExampleItem::settext(QString tmptext) | |
{ | |
this->text = tmptext; | |
} | |
ExampleTableModel::ExampleTableModel(QObject *parent) : | |
QAbstractTableModel(parent) | |
{ | |
header_data << QString::fromUtf8("Дата") << QString::fromUtf8("Время")<< QString::fromUtf8("Текст"); //тут записываем названия столбцов | |
db.open (path_db,"*.mdb"); | |
QList<QStringList> listnew = db.db_in_list (query_db); | |
for(int i = 0; i < listnew.count (); i++){ | |
ExampleItem* it = new ExampleItem; | |
it->settext (listnew.at (i).at (0)); | |
list.append(it); | |
} | |
} | |
QVariant ExampleTableModel::data(const QModelIndex &index, int role) const | |
{ | |
if (!index.isValid()) | |
return QVariant(); | |
if (index.row() >= list.size()) | |
return QVariant(); | |
// для каждого столбца возвращаем нужные данные | |
if (role == Qt::DisplayRole || role == Qt::EditRole){ | |
if (index.column() == 0 ) | |
return list.at(index.row())->date; | |
if (index.column() == 1 ) | |
return list.at(index.row())->time; | |
if (index.column() == 2 ) | |
return list.at(index.row())->text; | |
} | |
if (role == Qt::CheckStateRole){ | |
if (index.column() == 0 ){ | |
if (boolhash.contains (index)){ | |
return (boolhash.value (index)) ? Qt::Checked : Qt::Unchecked; | |
}else{ | |
return Qt::Unchecked; | |
} | |
} | |
} | |
return QVariant(); | |
} | |
bool ExampleTableModel::setData(const QModelIndex &index, const QVariant &value, int role) | |
{ | |
if (index.isValid() && role == Qt::EditRole) { | |
// записываем данные из каждого столбца | |
if(index.column()==0){ | |
list.at(index.row())->date = value.toString(); | |
} | |
if(index.column()==1){ | |
list.at(index.row())->time = value.toString(); | |
} | |
if(index.column()==2){ | |
list.at(index.row())->text = value.toString(); | |
} | |
return true; | |
} | |
if (index.isValid() && role == Qt::CheckStateRole) { | |
if(index.column()==0){ | |
bool state = (value==Qt::Checked?true:false); | |
if (boolhash.contains (index)){ | |
boolhash.remove (index); | |
}else{ | |
boolhash.insert(index,state); | |
} | |
} | |
return true; | |
} | |
return false; | |
} | |
void ExampleTableModel::setDatamod(QVariant value, int row, int col) | |
{ | |
this->list.at (row)->text = "fgfgfgfgf"; | |
} | |
int ExampleTableModel::rowCount(const QModelIndex &parent) const | |
{ | |
return list.size(); // размер списка - это количество строк | |
} | |
int ExampleTableModel::columnCount(const QModelIndex &parent) const | |
{ | |
return 3; // 3 столбца | |
} | |
bool ExampleTableModel::removeRows(int row, int count, const QModelIndex &parent) | |
{ | |
bool success =false; | |
beginRemoveRows(parent, row, row + count - 1); | |
for (int var = 0; var < count; ++var) { | |
list.removeAt (row+var); | |
} | |
success = true; | |
endRemoveRows(); | |
return success; | |
} | |
bool ExampleTableModel::insertRows(int row, int count, const QModelIndex &parent) | |
{ | |
bool success =false; | |
beginInsertRows(parent, row, row + count - 1); | |
for (int var = 0; var < count; ++var) { | |
if (!tmpadd.isNull ()){ | |
ExampleItem* newitem = new ExampleItem; | |
newitem->settext (tmpadd.toString ()); | |
list.insert (row+var, newitem);} | |
} | |
success = true; | |
endInsertRows(); | |
tmpadd.clear (); | |
return success; | |
} | |
bool ExampleTableModel::moveRows (const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild) | |
{ | |
beginMoveRows(sourceParent, sourceRow, sourceRow, destinationParent, destinationChild); | |
endMoveRows(); | |
return true; | |
} | |
QVariant ExampleTableModel::headerData(int section, Qt::Orientation orientation, int role) const | |
{ | |
if(role != Qt::DisplayRole) | |
return QVariant(); | |
if(orientation == Qt::Horizontal && role == Qt::DisplayRole){ | |
return header_data.at(section); // заголовки столбцов | |
}else{ | |
return QString("%1").arg( section + 1 ); // возвращаем номера строк | |
} | |
} | |
Qt::ItemFlags ExampleTableModel::flags(const QModelIndex &index) const | |
{ | |
if (!index.isValid()) | |
return Qt::ItemIsEnabled; | |
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable |Qt::ItemIsUserCheckable; | |
} | |
ExampleDelegate::ExampleDelegate() | |
{ | |
} | |
QWidget *ExampleDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const | |
{ | |
if (index.column() == 0) { // для первого столбца используем QDateTimeEdit | |
QDateTimeEdit *editor = new QDateTimeEdit(parent); | |
editor->setDisplayFormat("dd.MM.yyyy"); // формат даты | |
editor->setCalendarPopup(true); | |
editor->setDate(QDate::currentDate()); // устанавливаем дату по умолчанию | |
return editor; | |
}else if (index.column() == 1) { // для второго столбца используем QTimeEdit | |
QTimeEdit *editor = new QTimeEdit(parent); | |
editor->setDisplayFormat("hh.mm"); //формат для отображения времени | |
editor->setCalendarPopup(true); | |
return editor; | |
}else{ // для всех остальных устанавливаем QLineEdit | |
QLineEdit *editor = new QLineEdit(parent); | |
QString currentText = index.model()->data(index, Qt::DisplayRole).toString(); | |
editor->setText(currentText); | |
return editor; | |
} | |
} | |
void ExampleDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const | |
{ | |
if (index.column() == 0) { | |
QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor); | |
if (dateEditor) { | |
dateEditor->setDate(QDate::fromString(index.model()->data(index, Qt::EditRole).toString(),"d.MM.yyyy")); | |
} | |
}else if (index.column() == 1) { | |
QTimeEdit *timeEditor = qobject_cast<QTimeEdit *>(editor); | |
if (timeEditor) { | |
timeEditor->setTime(QTime::fromString(index.model()->data(index, Qt::EditRole).toString(),"hh.mm")); | |
timeEditor->setCurrentSectionIndex(1); | |
} | |
}else{ | |
QLineEdit *textEditor = qobject_cast<QLineEdit *>(editor); | |
if (textEditor) { | |
textEditor->setText(index.model()->data(index, Qt::EditRole).toString()); | |
} | |
} | |
} | |
void ExampleDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const | |
{ | |
if (index.column() == 0) { | |
QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor); | |
if (dateEditor) { | |
model->setData(index, dateEditor->date().toString("d.MM.yyyy")); // дату приводим к формату ДД.ММ.ГГГГ | |
} | |
}else if (index.column() == 1) { | |
QTimeEdit *timeEditor = qobject_cast<QTimeEdit *>(editor); | |
if (timeEditor) { | |
model->setData(index, timeEditor->time().toString("hh.mm")); // время приводим к формату ЧЧ.ММ | |
} | |
}else{ | |
QLineEdit *textEditor = qobject_cast<QLineEdit *>(editor); | |
if (textEditor) { | |
model->setData(index, textEditor->text()); | |
} | |
} | |
} | |
//----------------------------------------------------------- | |
MainWindow::MainWindow(QWidget *parent) | |
: QMainWindow(parent) | |
{ | |
QWidget* wi = new QWidget; | |
QVBoxLayout *layout_general = new QVBoxLayout(); | |
QPushButton *b_ok = new QPushButton("del current"); | |
QPushButton *b_ok1 = new QPushButton("add bef curr"); | |
QPushButton *b_ok2 = new QPushButton("update"); | |
connect (b_ok, SIGNAL(clicked()), this, SLOT(delcurrent())); | |
connect (b_ok1, SIGNAL(clicked()), this, SLOT(addbefcurrent())); | |
connect (b_ok2, SIGNAL(clicked()), this, SLOT(updatemod())); | |
table_view = new QTableView; | |
model = new ExampleTableModel; | |
table_view->setItemDelegate(new ExampleDelegate); // устанавливаем делегат представлению | |
table_view->setModel(model); // устанавливаем модель | |
layout_general->addWidget (table_view); | |
layout_general->addWidget (b_ok); | |
layout_general->addWidget (b_ok1); | |
layout_general->addWidget (b_ok2); | |
wi->setLayout (layout_general); | |
setCentralWidget(wi); // отображаем представление как центральный виджет | |
this->setWindowTitle ("Тестирование"); | |
QFutureWatcher<void> watcher; | |
connect (&watcher, SIGNAL(finished()), this, SLOT(close())); | |
QFuture<void> future = QtConcurrent::run(this,&MainWindow::serverCycle); | |
qApp->processEvents(); | |
} | |
void MainWindow::serverCycle() | |
{ | |
while (!flag_exit) { | |
Sleep(5000); | |
if (flag_exit) break; | |
qApp->processEvents(); | |
qDebug() << "work"; | |
//ghghghghghghgh//здесь вставить проверку базы и проверку екзитемзов, находим несовпадения с двух сторон и их колонки и в итемах удаляем а из базы вставляем в итемзы | |
} | |
} | |
MainWindow::~MainWindow() | |
{ | |
flag_exit=true; | |
db.close (); | |
qDebug() << "exit0"; | |
} | |
void MainWindow::delcurrent() | |
{ | |
//this->model->list.at (0)->settext ("бля"); | |
//this->model->setDatamod (QVariant("ggggg"),5,5); | |
this->model->removeRows (this->table_view->currentIndex ().row (),1,this->table_view->currentIndex ().parent ()); | |
} | |
void MainWindow::addbefcurrent() | |
{ | |
bool ok; | |
QStringList items; | |
items << "Да" << "Нет"; | |
QString answer = QInputDialog::getItem( this, "Ответ","Выберите:", items, 0, false, &ok); | |
if (ok && !items.isEmpty()) | |
{ | |
// double d = QInputDialog::getDouble(this, mi.model ()->index (var,0).data (0).toString (), "Объём за: "+month_, rand ()%1000+500, -1000000, 1000000, 0, &ok2); | |
// if (!ok) d=0; | |
this->model->tmpadd=QVariant("вот это " + answer); | |
this->model->insertRows (this->table_view->currentIndex ().row (),1,this->table_view->currentIndex ().parent ()); | |
} | |
} | |
void MainWindow::updatemod() | |
{ | |
this->model->moveRows (this->model->index (1,1),this->model->index (1,1).row (),this->model->index (2,1),this->model->index (2,1).row ()); | |
this->model->moveRows (this->model->index (2,1),this->model->index (2,1).row (),this->model->index (1,1),this->model->index (1,1).row ()); | |
} | |
//----------------------------------------------------------- | |
DataBase::DataBase() | |
{ | |
DataBase::db = QSqlDatabase::addDatabase(QLatin1String("QODBC")); | |
} | |
void DataBase::open(QString path,QString file_mask) | |
{ | |
QString connect = QString("DRIVER={Microsoft Access Driver (%2)};FIL={MS Access};DBQ=%1;").arg(path).arg(file_mask); //*.mdb | |
DataBase::db.setDatabaseName(connect); | |
if (!DataBase::db.open()) { | |
qDebug() << QString("DataBase Error: \n [%1] D'NOT Open!").arg(DataBase::path_db); | |
} | |
DataBase::path_db = path; | |
} | |
void DataBase::close() | |
{ | |
DataBase::db.close (); | |
} | |
void DataBase::do_this(QString query) | |
{ | |
QSqlQuery my_query(DataBase::db); | |
my_query.exec (query); | |
} | |
QList<QStringList> DataBase::db_in_list(QString query) | |
{ | |
QList<QStringList> list; | |
QStringList strlist; | |
QSqlQuery my_query(DataBase::db); | |
my_query.exec (query); | |
if (my_query.isActive()) { | |
QSqlRecord rec; | |
while (my_query.next()) { | |
rec = my_query.record(); | |
for (int var = 0; var < rec.count(); ++var) { | |
strlist << my_query.value (var).toString (); | |
} | |
list << strlist; | |
strlist.clear (); | |
} | |
} | |
return list; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef WIDGET_H | |
#define WIDGET_H | |
#include <QWidget> | |
#include <QString> | |
#include <QAbstractTableModel> | |
#include <QList> | |
#include <QStringList> | |
#include <QItemDelegate> | |
#include <QDateTimeEdit> | |
#include <QTimeEdit> | |
#include <QLineEdit> | |
#include <QMainWindow> | |
#include <QTableView> | |
#include <QtSql/QSqlDatabase> | |
#include <QtSql/QSqlRecord> | |
#include <QtSql/QSqlQuery> | |
#include <QtSql/QSql> | |
#include <QtSql/QSqlError> | |
#include <QtSql/QSqlQueryModel> | |
#include <QSettings> | |
#include <QDebug> | |
#include <QVBoxLayout> | |
#include <QTextCodec> | |
#include <QInputDialog> | |
#include <QThread> | |
#include <QtConcurrent/QtConcurrent> | |
#include <QFuture> | |
#include <QFutureWatcher> | |
namespace Ui { | |
class Widget; | |
} | |
class Widget : public QWidget | |
{ | |
Q_OBJECT | |
public: | |
explicit Widget(QWidget *parent = 0); | |
~Widget(); | |
private: | |
Ui::Widget *ui; | |
}; | |
//------------------------------------ | |
class ExampleItem | |
{ | |
public: | |
ExampleItem(); | |
QString time; //время | |
QString date; //дата | |
QString text; //текстовые данные | |
void settext(QString tmptext); | |
}; | |
//------------------------------------ | |
class ExampleTableModel : public QAbstractTableModel | |
{ | |
Q_OBJECT | |
public: | |
explicit ExampleTableModel(QObject *parent = 0); | |
QHash<QModelIndex,bool> boolhash; | |
QList<ExampleItem *> list; // список, в котором хранятся все данные | |
QStringList header_data; // список заголовков столбцов | |
QVariant tmpadd; | |
QVariant data(const QModelIndex &index, int role) const; | |
bool setData(const QModelIndex &index, const QVariant &value, int role); | |
void setDatamod(QVariant value, int row, int col); | |
int rowCount(const QModelIndex &parent=QModelIndex()) const; | |
int columnCount(const QModelIndex &parent) const; | |
bool removeRows (int row, int count, const QModelIndex &parent); | |
bool insertRows (int row, int count, const QModelIndex &parent); | |
bool moveRows (const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild); | |
QVariant headerData(int section,Qt::Orientation orientation, int role=Qt::DisplayRole) const; | |
Qt::ItemFlags flags(const QModelIndex &index) const; | |
signals: | |
public slots: | |
}; | |
//------------------------------------ | |
class ExampleDelegate : public QItemDelegate | |
{ | |
public: | |
ExampleDelegate(); | |
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; | |
void setEditorData(QWidget *editor, const QModelIndex &index) const; | |
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; | |
}; | |
//------------------------------------ | |
class MainWindow : public QMainWindow | |
{ | |
Q_OBJECT | |
public: | |
MainWindow(QWidget *parent = 0); | |
~MainWindow(); | |
QTableView* table_view; // представление | |
ExampleTableModel* model; // модель | |
public slots: | |
void delcurrent(); | |
void addbefcurrent(); | |
void updatemod(); | |
void serverCycle(); | |
}; | |
//------------------------------------ | |
class DataBase | |
{ | |
public: | |
DataBase(); | |
void open(QString, QString); | |
void close(); | |
void do_this(QString); | |
QList<QStringList> db_in_list(QString); | |
QString path_db; | |
QSqlDatabase db; | |
}; | |
//------------------------------------ | |
#endif // WIDGET_H |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
QModelIndex |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment