когда таблица фокус теряет, вроде как виджет-редактор закрывается, т.е. уже представление сигнал посылает.
когда таблица фокус теряет, вроде как виджет-редактор закрывается, т.е. уже представление сигнал посылает.
Но в моем случае почему-то только после нажатия ентер срабатывает. А при потере таблицей фокуса нет :(
Вот код:
Делегат
C++ (Qt)
LineEditDelegate::LineEditDelegate(QObject *parent):
QItemDelegate(parent)
{
}
LineEditDelegate::~LineEditDelegate()
{
}
QWidget *LineEditDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QLineEdit *le = new QLineEdit(parent);
connect(le,SIGNAL(editingFinished()),this,SIGNAL(editingFinished()));
return le;
//QRegExp rx("[a-zA-Zа-яА-Я0-9]{1,12}");
//QValidator *validator = new QRegExpValidator(rx,(QObject*)this);
//le->setValidator(validator);
}
void LineEditDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString string = index.model()->data(index).toString();
QLineEdit *le = static_cast<QLineEdit* >(editor);
le->setStyleSheet("*{selection-background-color: green}");
le->setText(string);
}
void LineEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
qDebug()<<__FUNCTION__;
QLineEdit *le = static_cast<QLineEdit* >(editor);
QString str = le->text();
model->setData(index,str);
}
bool LineEditDelegate::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::KeyPress)
emit editingStarted();
return QItemDelegate::eventFilter(object,event);
}
Модель
C++ (Qt)
QVariant TableModelPrKey::data(const QModelIndex &index, int role) const
{
return BaseDataTableModel::data(index,role);
}
bool TableModelPrKey::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(index.isValid()){
dataRecords.at(index.row())->operator [](index.column()) = value.toString();
if(index.row() < countDataBaseRecords){
QModelIndex primaryKeyIndex = QAbstractTableModel::index(index.row(),columnFieldCode());
//QModelIndex primaryKeyIndex = QAbstractTableModel::index(index.row(),0);
id = data(primaryKeyIndex).toInt();//int id = data(primaryKeyIndex).toInt();
qDebug()<<id;
qDebug()<<nameTable;
qDebug()<<query.record().fieldName(index.column());
//QSqlQuery query_set_data;
//query_set_data.prepare("UPDATE " + nameTable + " SET " + query.record().fieldName(index.column()) + " = ? WHERE CODE = ?");
if(!modeEdit){
modeEdit = true;
updateQuery.clear();
updateQuery = "UPDATE " + nameTable + " SET ";
}
else{
updateQuery.append(",");
}
QString str;
QVariant::Type fieldType = query.record().field(query.record().fieldName(index.column())).type();
switch(fieldType){
case QVariant::Int: {
str = QString(query.record().fieldName(index.column()) + " = %1 ").arg(value.toInt());
break;
}
case QVariant::String: {
str = QString(query.record().fieldName(index.column()) + " ='%1' ").arg(value.toString());
break;
}
case QVariant::Double: {
str = QString(query.record().fieldName(index.column()) + " = %1 ").arg(value.toFloat());
break;
}
default: break;
}
updateQuery.append(str);
return true;
}
return true;
}
return false;
}
void TableModelPrKey::queryUpdateRecord()
{
QString str = QString("WHERE CODE = %1").arg(id);
updateQuery.append(str);
QSqlQuery query_update;
QSqlDatabase::database().transaction();
try{
if(!updateQuery.isNull()){
if(!query_update.exec(updateQuery)){
throw (char*)"Error";
}
QSqlDatabase::database().commit();
}
}
catch(char*){
QMessageBox::critical(0,nameTable,query_update.lastError().text(),QMessageBox::Ok);//qCritical()<<query_update.lastError().text();
QSqlDatabase::database().rollback();
}
updateQuery.clear();
modeEdit = false;
}
Вьюха
C++ (Qt)
void TableView::keyPressEvent(QKeyEvent *event)
{
BaseDataTableModel* dataBaseModel = (BaseDataTableModel*)(((DataBaseFilterModel*)model())->sourceModel());
switch(event->key()){
case Qt::Key_Insert:{
switch(mode){
case BROWSE:{
//идет приготовление данных для добавления в базу
qDebug()<<"insert";
dataBaseModel->prepareInsertData();
int row = dataBaseModel->rowCount(QModelIndex());
if(row > dataBaseModel->getCountDataBaseRecords()){
QModelIndex index = ((DataBaseFilterModel*)model())->mapFromSource(dataBaseModel->index(row - 1,1));
selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows);
setCurrentIndex(index);
previous = current = index;
scrollToBottom();
edit(index);
mode = INSERT;
}
break;
}
case EDIT:{
break;
}
case INSERT:{
break;
}
default:{
break;
}
}
break;
}
case Qt::Key_Escape:{
switch(mode){
case BROWSE:{
// ничего
break;
}
case EDIT:{
// ничего
break;
}
case INSERT:{
//сброс режима, удаление вставляеой записи
dataBaseModel->cancelInsertData();
mode = BROWSE;
break;
}
default: break;
}
break;
}
case Qt::Key_Delete:{
if(event->modifiers() == Qt::ControlModifier){
qDebug()<<"cntrl + delete";
if(clickedIndex.isValid())
dataBaseModel->deleteData(clickedIndex);
clickedIndex = QModelIndex();
}
break;
}
case Qt::Key_F:{
if(event->modifiers() == Qt::ControlModifier){
if(clickedIndex.isValid()){
column = clickedIndex.column();
nameColumn = ((BaseDataTableModel*)(((DataBaseFilterModel*)model())->sourceModel()))->query.record().fieldName(column);
QString nameTable = ((BaseDataTableModel*)(((DataBaseFilterModel*)model())->sourceModel()))->getNameTable();
//selectionModel()->select(clickedIndex, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Columns)//для выделения целой колонки
Dialog finder(nameTable,nameColumn,column);
connect(&finder,SIGNAL(changeFilter(QString ,int)),((DataBaseFilterModel*)model()),SLOT(updateFilterColumn(QString ,int)));
connect(&finder,SIGNAL(updateView()),viewport(),SLOT(update()));
connect(&finder,SIGNAL(closeDialog()),((DataBaseFilterModel*)model()),SLOT(resetFilterColumn()));
finder.exec();
}
}
break;
}
case Qt::Key_Up:{
switch(mode){
case BROWSE:{
break;
}
case EDIT:{
dataBaseModel->queryUpdateRecord();
mode = BROWSE;
break;
}
case INSERT:{
if(dataBaseModel->insertData() > 0){
mode = BROWSE;
}
else{
int row = dataBaseModel->rowCount(QModelIndex());
QModelIndex index = ((DataBaseFilterModel*)model())->mapFromSource(dataBaseModel->index(row - 1,1));
selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows);
//setCurrentIndex(index);
}
break;
}
default: break;
}
break;
}
case Qt::Key_Down:{
switch(mode){
case BROWSE:{
break;
}
case EDIT:{
dataBaseModel->queryUpdateRecord();
mode = BROWSE;
break;
}
case INSERT:{
if(dataBaseModel->insertData() > 0){
mode = BROWSE;
}
else{
int row = dataBaseModel->rowCount(QModelIndex());
QModelIndex index = ((DataBaseFilterModel*)model())->mapFromSource(dataBaseModel->index(row - 1,1));
selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows);
//setCurrentIndex(index);
}
break;
}
default: break;
}
break;
}
default:
break;
}
QTableView::keyPressEvent(event);
emit currentIndexChanged(currentIndex());
}
void TableView::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton){
BaseDataTableModel* dataBaseModel = (BaseDataTableModel*)(((DataBaseFilterModel*)model())->sourceModel());
clickedIndex = ((DataBaseFilterModel*)model())->mapToSource(indexAt(event->pos())); //заменить потом на current
current = ((DataBaseFilterModel*)model())->mapToSource(indexAt(event->pos()));
qDebug()<<"current = "<<current;
qDebug()<<"previous = "<<previous;
if(previous.row() != current.row()){
switch(mode){
case BROWSE:{
break;
}
case EDIT:{
dataBaseModel->queryUpdateRecord();
mode = BROWSE;
break;
}
case INSERT:{
if(dataBaseModel->insertData() > 0){
mode = BROWSE;
}
else{
int row = dataBaseModel->rowCount(QModelIndex());
QModelIndex index = ((DataBaseFilterModel*)model())->mapFromSource(dataBaseModel->index(row - 1,1));
selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows);
scrollToBottom();
current = previous;
setCurrentIndex(current);
return;
}
break;
}
default: break;
}
if(!current.isValid() && previous.isValid()){
current = previous;
selectionModel()->setCurrentIndex(previous, QItemSelectionModel::ClearAndSelect/*|QItemSelectionModel::Rows*/);
setCurrentIndex(previous);
}
else{
previous = current;
}
emit currentIndexChanged(current);//emit currentIndexChanged(clickedIndex);
}
else{
if(!current.isValid() && previous.isValid()){
current = previous;
selectionModel()->setCurrentIndex(previous, QItemSelectionModel::ClearAndSelect/*|QItemSelectionModel::Rows*/);
setCurrentIndex(previous);
}
else{
previous = current;
}
}
//if(current.isValid()) //???может убрать->надо протестить???
// previous = current;
//if(event->button() == Qt::LeftButton){
// if(clickedIndex.isValid()){
// emit currentIndexChanged(clickedIndex);
// }
//}
}
QTableView::mousePressEvent(event);
}
void TableView::mouseDoubleClickEvent(QMouseEvent *event)
{
qDebug()<<__FUNCTION__;
BaseDataTableModel* dataBaseModel = (BaseDataTableModel*)(((DataBaseFilterModel*)model())->sourceModel());
current = ((DataBaseFilterModel*)model())->mapToSource(indexAt(event->pos()));
qDebug()<<"current = "<<current;
qDebug()<<"previous = "<<previous;
editing = true;
switch(mode){
case BROWSE:{
qDebug()<<"mode = EDIT";
mode = EDIT;
//previous = current;
break;
}
case EDIT:{
if(previous.row() != current.row()){
dataBaseModel->queryUpdateRecord();
//previous = current;
}
break;
}
case INSERT:{
if(previous.row() != current.row()){
if(dataBaseModel->insertData() > 0){
mode = EDIT;
//previous = current;
}
else{
int row = dataBaseModel->rowCount(QModelIndex());
QModelIndex index = ((DataBaseFilterModel*)model())->mapFromSource(dataBaseModel->index(row - 1,1));
selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows);
scrollToBottom();
current = previous;
setCurrentIndex(current);
return;
}
}
break;
}
default: break;
}
//previous = current;
QTableView::mouseDoubleClickEvent(event);
}
void TableView::focusOutEvent(QFocusEvent *event)
{
BaseDataTableModel* dataBaseModel = (BaseDataTableModel*)(((DataBaseFilterModel*)model())->sourceModel());
switch(mode){
case BROWSE:{
break;
}
case EDIT:{
if(!editing){
dataBaseModel->queryUpdateRecord();
mode = BROWSE;
//editing = false;
}
break;
}
case INSERT:{
if(!editing){
dataBaseModel->insertData();
mode = BROWSE;
//editing = false;
}
break;
}
default: break;
}
QTableView::focusOutEvent(event);
}
void TableView::editingStarted()
{
editing = true;
}
void TableView::editingFinished()
{
editing = false;
}
Фрейм_Таб
C++ (Qt)
void FrameTab1::CreateDevicesTable()
{
LineEditDelegate *leDelegate = new LineEditDelegate(this);
connect(leDelegate,SIGNAL(editingStarted()),ui.tableViewCP_Device,SLOT(editingStarted())); //можно убрать
connect(leDelegate,SIGNAL(editingFinished()),ui.tableViewCP_Device,SLOT(editingFinished())); ////можно убрать
ComboBoxDelegate *cbDelegateDevices = new ComboBoxDelegate(DEVICES,this);
dbModel_Devices = new TableModelPrKey(DEVICES,this);
//connect(dbModel_Devices,SIGNAL(sqlQueryError(QString,QString)),this,SLOT(sqlQueryError(QString,QString)));
proxyModel_Devices = new DataBaseFilterModel(this);
proxyModel_Devices->setSourceModel(dbModel_Devices);
ui.tableViewDevices->setModel(proxyModel_Devices);
ui.tableViewDevices->setItemDelegateForColumn(1,leDelegate);
ui.tableViewDevices->setItemDelegateForColumn(2,leDelegate);
ui.tableViewDevices->setItemDelegateForColumn(5,leDelegate);
ui.tableViewDevices->setItemDelegateForColumn(6,leDelegate);
ui.tableViewDevices->setItemDelegateForColumn(7,leDelegate);
ui.tableViewDevices->setItemDelegateForColumn(8,leDelegate);
ui.tableViewDevices->setItemDelegateForColumn(11,leDelegate);
ui.tableViewDevices->setItemDelegateForColumn(3,cbDelegateDevices);
ui.tableViewDevices->setItemDelegateForColumn(4,cbDelegateDevices);
ui.tableViewDevices->setItemDelegateForColumn(9,cbDelegateDevices);
ui.tableViewDevices->setItemDelegateForColumn(10,cbDelegateDevices);
...
}