Новичок
Группа: Новичок
Сообщений: 1
Регистрация: 26.2.2013
Пользователь №: 3729
Спасибо сказали: 0 раз(а)
Репутация: 0
|
Добрый вечер. Подскажите пожалуйста. В Qt имеется пример на основе tableview, который бы я хотел впихнуть в свою программу. Дабы не загромождать код, я хочу чтобы в главном окне отображалось только представление(view). Вопрос как прописать? bookwindow.cpp #include "bookwindow.h" #include "bookdelegate.h" #include "initdb.h"
#include <QtSql>
BookWindow::BookWindow() { ui.setupUi(this);
if (!QSqlDatabase::drivers().contains("QSQLITE")) QMessageBox::critical(this, "Unable to load database", "This demo needs the SQLITE driver");
// initialize the database QSqlError err = initDb(); if (err.type() != QSqlError::NoError) { showError(err); return; }
// Create the data model model = new QSqlRelationalTableModel(ui.bookTable); model->setEditStrategy(QSqlTableModel::OnManualSubmit); model->setTable("books");
// Remember the indexes of the columns authorIdx = model->fieldIndex("author"); genreIdx = model->fieldIndex("genre");
// Set the relations to the other database tables model->setRelation(authorIdx, QSqlRelation("authors", "id", "name")); model->setRelation(genreIdx, QSqlRelation("genres", "id", "name"));
// Set the localized header captions model->setHeaderData(authorIdx, Qt::Horizontal, tr("Author Name")); model->setHeaderData(genreIdx, Qt::Horizontal, tr("Genre")); model->setHeaderData(model->fieldIndex("title"), Qt::Horizontal, tr("Title")); model->setHeaderData(model->fieldIndex("year"), Qt::Horizontal, tr("Year")); model->setHeaderData(model->fieldIndex("rating"), Qt::Horizontal, tr("Rating"));
// Populate the model if (!model->select()) { showError(model->lastError()); return; }
// Set the model and hide the ID column ui.bookTable->setModel(model); ui.bookTable->setItemDelegate(new BookDelegate(ui.bookTable)); ui.bookTable->setColumnHidden(model->fieldIndex("id"), true); ui.bookTable->setSelectionMode(QAbstractItemView::SingleSelection);
// Initialize the Author combo box ui.authorEdit->setModel(model->relationModel(authorIdx)); ui.authorEdit->setModelColumn(model->relationModel(authorIdx)->fieldIndex("name"));
ui.genreEdit->setModel(model->relationModel(genreIdx)); ui.genreEdit->setModelColumn(model->relationModel(genreIdx)->fieldIndex("name"));
QDataWidgetMapper *mapper = new QDataWidgetMapper(this); mapper->setModel(model); mapper->setItemDelegate(new BookDelegate(this)); mapper->addMapping(ui.titleEdit, model->fieldIndex("title")); mapper->addMapping(ui.yearEdit, model->fieldIndex("year")); mapper->addMapping(ui.authorEdit, authorIdx); mapper->addMapping(ui.genreEdit, genreIdx); mapper->addMapping(ui.ratingEdit, model->fieldIndex("rating"));
connect(ui.bookTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), mapper, SLOT(setCurrentModelIndex(QModelIndex)));
ui.bookTable->setCurrentIndex(model->index(0, 0)); }
void BookWindow::showError(const QSqlError &err) { QMessageBox::critical(this, "Unable to initialize Database", "Error initializing database: " + err.text()); }
bookwindow.h #ifndef BOOKWINDOW_H #define BOOKWINDOW_H
#include <QtGui> #include <QtSql>
#include "ui_bookwindow.h"
class BookWindow: public QMainWindow { Q_OBJECT public: BookWindow();
private: void showError(const QSqlError &err); Ui::BookWindow ui; QSqlRelationalTableModel *model; int authorIdx, genreIdx; };
#endif
bookdelegate.h #ifndef BOOKDELEGATE_H #define BOOKDELEGATE_H
#include <QModelIndex> #include <QPixmap> #include <QSize> #include <QSqlRelationalDelegate>
QT_FORWARD_DECLARE_CLASS(QPainter)
class BookDelegate : public QSqlRelationalDelegate { public: BookDelegate(QObject *parent);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
private: QPixmap star; };
#endif
bookdelegate.cpp #include "bookdelegate.h"
#include <QtGui>
BookDelegate::BookDelegate(QObject *parent) : QSqlRelationalDelegate(parent), star(QPixmap(":images/star.png")) { }
void BookDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.column() != 5) { QStyleOptionViewItemV3 opt = option; opt.rect.adjust(0, 0, -1, -1); // since we draw the grid ourselves QSqlRelationalDelegate::paint(painter, opt, index); } else { const QAbstractItemModel *model = index.model(); QPalette::ColorGroup cg = (option.state & QStyle::State_Enabled) ? (option.state & QStyle::State_Active) ? QPalette::Normal : QPalette::Inactive : QPalette::Disabled;
if (option.state & QStyle::State_Selected) painter->fillRect(option.rect, option.palette.color(cg, QPalette::Highlight));
int rating = model->data(index, Qt::DisplayRole).toInt(); int width = star.width(); int height = star.height(); int x = option.rect.x(); int y = option.rect.y() + (option.rect.height() / 2) - (height / 2); for (int i = 0; i < rating; ++i) { painter->drawPixmap(x, y, star); x += width; } drawFocus(painter, option, option.rect.adjusted(0, 0, -1, -1)); // since we draw the grid ourselves }
QPen pen = painter->pen(); painter->setPen(option.palette.color(QPalette::Mid)); painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); painter->drawLine(option.rect.topRight(), option.rect.bottomRight()); painter->setPen(pen); }
QSize BookDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.column() == 5) return QSize(5 * star.width(), star.height()) + QSize(1, 1);
return QSqlRelationalDelegate::sizeHint(option, index) + QSize(1, 1); // since we draw the grid ourselves }
bool BookDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) { if (index.column() != 5) return QSqlRelationalDelegate::editorEvent(event, model, option, index);
if (event->type() == QEvent::MouseButtonPress) { QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); int stars = qBound(0, int(0.7 + qreal(mouseEvent->pos().x() - option.rect.x()) / star.width()), 5); model->setData(index, QVariant(stars)); return false; //so that the selection can change }
return true; }
QWidget *BookDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.column() != 4) return QSqlRelationalDelegate::createEditor(parent, option, index);
// for editing the year, return a spinbox with a range from -1000 to 2100. QSpinBox *sb = new QSpinBox(parent); sb->setFrame(false); sb->setMaximum(2100); sb->setMinimum(-1000);
return sb; }
|