📄 artistform.cpp
字号:
#include <QtGui>#include <QtSql>#include "artistform.h"#include "generateid.h"ArtistForm::ArtistForm(const QString &name, QWidget *parent) : QDialog(parent){ model = new QSqlTableModel(this); model->setTable("artist"); model->setSort(Artist_Name, Qt::AscendingOrder); model->setHeaderData(Artist_Name, Qt::Horizontal, tr("Name")); model->setHeaderData(Artist_Country, Qt::Horizontal, tr("Country")); model->select(); connect(model, SIGNAL(beforeInsert(QSqlRecord &)), this, SLOT(beforeInsertArtist(QSqlRecord &))); tableView = new QTableView; tableView->setModel(model); tableView->setColumnHidden(Artist_Id, true); tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->resizeColumnsToContents(); for (int row = 0; row < model->rowCount(); ++row) { QSqlRecord record = model->record(row); if (record.value(Artist_Name).toString() == name) { tableView->selectRow(row); break; } } addButton = new QPushButton(tr("&Add")); deleteButton = new QPushButton(tr("&Delete")); closeButton = new QPushButton(tr("Close")); connect(addButton, SIGNAL(clicked()), this, SLOT(addArtist())); connect(deleteButton, SIGNAL(clicked()), this, SLOT(deleteArtist())); connect(closeButton, SIGNAL(clicked()), this, SLOT(accept())); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addWidget(addButton); buttonLayout->addWidget(deleteButton); buttonLayout->addStretch(); buttonLayout->addWidget(closeButton); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(tableView); mainLayout->addLayout(buttonLayout); setLayout(mainLayout); setWindowTitle(tr("Edit Artists"));}void ArtistForm::addArtist(){ int row = model->rowCount(); model->insertRow(row); QModelIndex index = model->index(row, Artist_Name); tableView->setCurrentIndex(index); tableView->edit(index);}void ArtistForm::beforeInsertArtist(QSqlRecord &record){ record.setValue("id", generateId("artist"));}void ArtistForm::deleteArtist(){ tableView->setFocus(); QModelIndex index = tableView->currentIndex(); if (!index.isValid()) return; QSqlRecord record = model->record(index.row()); QSqlTableModel cdModel; cdModel.setTable("cd"); cdModel.setFilter("artistid = " + record.value("id").toString()); cdModel.select(); if (cdModel.rowCount() == 0) { model->removeRow(tableView->currentIndex().row()); } else { QMessageBox::information(this, tr("Delete Artist"), tr("Cannot delete %1 because there are CDs associated " "with this artist in the collection.") .arg(record.value("name").toString())); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -