GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — sqlitebrowser/src/ExtendedTableWidget.cpp at master · sqlitebrowser/sqlitebrowser Expand file tree/ Copy pathExtendedTableWidget.cppMore file actions 1367 lines (1171 loc) · 57.1 KB / Copy pathExtendedTableWidget.cppFile metadata and controls1367 lines (1171 loc) · 57.1 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 #include "ExtendedTableWidget.h" #include "sqlitetablemodel.h" #include "FilterTableHeader.h" #include "sql/sqlitetypes.h" #include "Settings.h" #include "sqlitedb.h" #include "CondFormat.h" #include "Data.h" #include <QApplication> #include <QClipboard> #include <QMimeData> #include <QKeySequence> #include <QKeyEvent> #include <QScrollBar> #include <QHeaderView> #include <QMessageBox> #include <QBuffer> #include <QMenu> #include <QDateTime> #include <QLineEdit> #include <QPrinter> #include <QPrintPreviewDialog> #include <QTextDocument> #include <QCompleter> #include <QComboBox> #include <QPainter> #include <QShortcut> #include <QProgressDialog> #include <limits> using BufferRow = std::vector<QByteArray>; std::vector<BufferRow> ExtendedTableWidget::m_buffer; QString ExtendedTableWidget::m_generatorStamp; UniqueFilterModel::UniqueFilterModel(QObject* parent) : QSortFilterProxyModel(parent) { } bool UniqueFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, filterKeyColumn(), sourceParent); const std::string value = index.data(Qt::EditRole).toString().toStdString(); if (!value.empty() && m_uniqueValues.find(value) == m_uniqueValues.end()) { const_cast<UniqueFilterModel*>(this)->m_uniqueValues.insert(value); return true; } else return false; } ExtendedTableWidgetEditorDelegate::ExtendedTableWidgetEditorDelegate(QObject* parent) : QStyledItemDelegate(parent) { } QWidget* ExtendedTableWidgetEditorDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& /*option*/, const QModelIndex& index) const { emit dataAboutToBeEdited(index); SqliteTableModel* m = qobject_cast<SqliteTableModel*>(const_cast<QAbstractItemModel*>(index.model())); auto fk = m->getForeignKeyClause(static_cast<size_t>(index.column()-1)); if(fk) { sqlb::ObjectIdentifier foreignTable = sqlb::ObjectIdentifier(m->currentTableName().schema(), fk->table()); std::string column; // If no column name is set, assume the primary key is meant if(fk->columns().empty()) { sqlb::TablePtr obj = m->db().getTableByName(foreignTable); column = obj->primaryKeyColumns().front().name(); } else column = fk->columns().at(0); sqlb::TablePtr currentTable = m->db().getTableByName(m->currentTableName()); QString query = QString("SELECT %1 FROM %2").arg(QString::fromStdString(sqlb::escapeIdentifier(column)), QString::fromStdString(foreignTable.toString())); // if the current column of the current table does NOT have not-null constraint, // the NULL is united to the query to get the possible values in the combo-box. if (!currentTable->fields.at(static_cast<size_t>(index.column())-1).notnull()) query.append (" UNION SELECT NULL"); SqliteTableModel* fkModel = new SqliteTableModel(m->db(), parent, m->encoding()); fkModel->setQuery(query); QComboBox* combo = new QComboBox(parent); // Complete cache so it is ready when setEditorData is invoked. fkModel->completeCache(); combo->setModel(fkModel); return combo; } else { QLineEdit* editor = new QLineEdit(parent); // If the row count is not greater than the complete threshold setting, set a completer of values based on current values in the column. if (index.model()->rowCount() <= Settings::getValue("databrowser", "complete_threshold").toInt()) { QCompleter* completer = new QCompleter(editor); UniqueFilterModel* completerFilter = new UniqueFilterModel(completer); // Provide a filter for the source model, so only unique and non-empty values are accepted. completerFilter->setSourceModel(const_cast<QAbstractItemModel*>(index.model())); completerFilter->setFilterKeyColumn(index.column()); completer->setModel(completerFilter); // Complete on this column, using a popup and case-insensitively. completer->setCompletionColumn(index.column()); completer->setCompletionMode(QCompleter::PopupCompletion); completer->setCaseSensitivity(Qt::CaseInsensitive); editor->setCompleter(completer); CompleterTabKeyPressedEventFilter* completerTabHandleFilter = new CompleterTabKeyPressedEventFilter(completer); completer->popup()->installEventFilter(completerTabHandleFilter); } // Set the maximum length to the highest possible value instead of the default 32768. editor->setMaxLength(std::numeric_limits<int>::max()); return editor; } } void ExtendedTableWidgetEditorDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { QLineEdit* lineedit = dynamic_cast<QLineEdit*>(editor); // Set the data for the editor QString data = index.data(Qt::EditRole).toString(); if(!lineedit) { QComboBox* combo = static_cast<QComboBox*>(editor); int comboIndex = combo->findText(data); if (comboIndex >= 0) // if it is valid, adjust the combobox combo->setCurrentIndex(comboIndex); } else { lineedit->setText(data); // Put the editor in read only mode if the actual data is larger than the maximum length to avoid accidental truncation of the data lineedit->setReadOnly(data.size() > lineedit->maxLength()); } } void ExtendedTableWidgetEditorDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const { // Only apply the data back to the model if the editor is not in read only mode to avoid accidental truncation of the data QLineEdit* lineedit = dynamic_cast<QLineEdit*>(editor); if(!lineedit) { QComboBox* combo = static_cast<QComboBox*>(editor); model->setData(index, combo->currentData(Qt::EditRole), Qt::EditRole); } else if(!lineedit->isReadOnly()) model->setData(index, lineedit->text()); } void ExtendedTableWidgetEditorDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& /*index*/) const { editor->setGeometry(option.rect); } class ItemBorderDelegate : public QStyledItemDelegate { public: explicit ItemBorderDelegate(QObject* parent = nullptr) : QStyledItemDelegate(parent) { } void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override { QStyledItemDelegate::paint(painter, option, index); QRect border(option.rect); border.translate(border.width() - 1, 0); border.setWidth(2); painter->fillRect(border, Qt::black); } }; ExtendedTableWidget::ExtendedTableWidget(QWidget* parent) : QTableView(parent), m_frozen_table_view(qobject_cast<ExtendedTableWidget*>(parent) ? nullptr : new ExtendedTableWidget(this)), m_frozen_column_count(0), m_item_border_delegate(new ItemBorderDelegate(this)) { setWordWrap(Settings::getValue("databrowser", "cell_word_wrap").toBool()); setHorizontalScrollMode(ExtendedTableWidget::ScrollPerPixel); // Force ScrollPerItem, so scrolling shows all table rows setVerticalScrollMode(ExtendedTableWidget::ScrollPerItem); connect(verticalScrollBar(), &QScrollBar::valueChanged, this, &ExtendedTableWidget::vscrollbarChanged); connect(this, &ExtendedTableWidget::clicked, this, &ExtendedTableWidget::cellClicked); // Set up filter row m_tableHeader = new FilterTableHeader(this); setHorizontalHeader(m_tableHeader); // Disconnect clicking in header to select column, since we will use it for sorting. // Note that, in order to work, this cannot be converted to the standard C++11 format. disconnect(m_tableHeader, SIGNAL(sectionPressed(int)),this, SLOT(selectColumn(int))); // Set up vertical header context menu verticalHeader()->setContextMenuPolicy(Qt::CustomContextMenu); // Set up table view context menu m_contextMenu = new QMenu(this); QAction* filterAction = new QAction(QIcon(":/icons/filter"), tr("Use as Exact Filter"), m_contextMenu); QAction* containingAction = new QAction(tr("Containing"), m_contextMenu); QAction* notContainingAction = new QAction(tr("Not containing"), m_contextMenu); QAction* notEqualToAction = new QAction(tr("Not equal to"), m_contextMenu); QAction* greaterThanAction = new QAction(tr("Greater than"), m_contextMenu); QAction* lessThanAction = new QAction(tr("Less than"), m_contextMenu); QAction* greaterEqualAction = new QAction(tr("Greater or equal"), m_contextMenu); QAction* lessEqualAction = new QAction(tr("Less or equal"), m_contextMenu); QAction* inRangeAction = new QAction(tr("Between this and..."), m_contextMenu); QAction* regexpAction = new QAction(tr("Regular expression"), m_contextMenu); QAction* condFormatAction = new QAction(QIcon(":/icons/edit_cond_formats"), tr("Edit Conditional Formats..."), m_contextMenu); QAction* nullAction = new QAction(QIcon(":/icons/set_to_null"), tr("Set to NULL"), m_contextMenu); QAction* cutAction = new QAction(QIcon(":/icons/cut"), tr("Cut"), m_contextMenu); QAction* copyAction = new QAction(QIcon(":/icons/copy"), tr("Copy"), m_contextMenu); QAction* copyWithHeadersAction = new QAction(QIcon(":/icons/special_copy"), tr("Copy with Headers"), m_contextMenu); QAction* copyAsSQLAction = new QAction(QIcon(":/icons/sql_copy"), tr("Copy as SQL"), m_contextMenu); QAction* pasteAction = new QAction(QIcon(":/icons/paste"), tr("Paste"), m_contextMenu); QAction* printAction = new QAction(QIcon(":/icons/print"), tr("Print..."), m_contextMenu); m_contextMenu->addAction(filterAction); QMenu* filterMenu = m_contextMenu->addMenu(tr("Use in Filter Expression")); filterMenu->addAction(containingAction); filterMenu->addAction(notContainingAction); filterMenu->addAction(notEqualToAction); filterMenu->addAction(greaterThanAction); filterMenu->addAction(lessThanAction); filterMenu->addAction(greaterEqualAction); filterMenu->addAction(lessEqualAction); filterMenu->addAction(inRangeAction); filterMenu->addAction(regexpAction); m_contextMenu->addAction(condFormatAction); m_contextMenu->addSeparator(); m_contextMenu->addAction(nullAction); m_contextMenu->addSeparator(); m_contextMenu->addAction(cutAction); m_contextMenu->addAction(copyAction); m_contextMenu->addAction(copyWithHeadersAction); m_contextMenu->addAction(copyAsSQLAction); m_contextMenu->addAction(pasteAction); m_contextMenu->addSeparator(); m_contextMenu->addAction(printAction); setContextMenuPolicy(Qt::CustomContextMenu); // Create and set up delegate m_editorDelegate = new ExtendedTableWidgetEditorDelegate(this); setItemDelegate(m_editorDelegate); connect(m_editorDelegate, &ExtendedTableWidgetEditorDelegate::dataAboutToBeEdited, this, &ExtendedTableWidget::dataAboutToBeEdited); // This is only for displaying the shortcut in the context menu. // An entry in keyPressEvent is still needed. nullAction->setShortcut(QKeySequence(tr("Alt+Del"))); cutAction->setShortcut(QKeySequence::Cut); copyAction->setShortcut(QKeySequence::Copy); copyWithHeadersAction->setShortcut(QKeySequence(tr("Ctrl+Shift+C"))); copyAsSQLAction->setShortcut(QKeySequence(tr("Ctrl+Alt+C"))); pasteAction->setShortcut(QKeySequence::Paste); printAction->setShortcut(QKeySequence::Print); // Set up context menu actions connect(this, &QTableView::customContextMenuRequested, this, [=](const QPoint& pos) { // Deactivate context menu options if there is no model set bool enabled = model(); filterAction->setEnabled(enabled); filterMenu->setEnabled(enabled); copyAction->setEnabled(enabled); copyWithHeadersAction->setEnabled(enabled); copyAsSQLAction->setEnabled(enabled); printAction->setEnabled(enabled); condFormatAction->setEnabled(enabled); // Hide filter actions when there isn't any filters bool hasFilters = m_tableHeader->hasFilters(); filterAction->setVisible(hasFilters); filterMenu->menuAction()->setVisible(hasFilters); condFormatAction->setVisible(hasFilters); // Try to find out whether the current view is editable and (de)activate menu options according to that bool editable = editTriggers() != QAbstractItemView::NoEditTriggers; nullAction->setEnabled(enabled && editable); cutAction->setEnabled(enabled && editable); pasteAction->setEnabled(enabled && editable); // Show menu m_contextMenu->popup(viewport()->mapToGlobal(pos)); }); connect(filterAction, &QAction::triggered, this, [&]() { useAsFilter(QString ("=")); }); connect(containingAction, &QAction::triggered, this, [&]() { useAsFilter(QString ("")); }); // Use a regular expression for the not containing filter. Simplify this if we ever support the NOT LIKE filter. connect(notContainingAction, &QAction::triggered, this, [&]() { useAsFilter(QString ("/^((?!"), /* binary */ false, QString (").)*$/")); }); connect(notEqualToAction, &QAction::triggered, this, [&]() { useAsFilter(QString ("<>")); }); connect(greaterThanAction, &QAction::triggered, this, [&]() { useAsFilter(QString (">")); }); connect(lessThanAction, &QAction::triggered, this, [&]() { useAsFilter(QString ("<")); }); connect(greaterEqualAction, &QAction::triggered, this, [&]() { useAsFilter(QString (">=")); }); connect(lessEqualAction, &QAction::triggered, this, [&]() { useAsFilter(QString ("<=")); }); connect(inRangeAction, &QAction::triggered, this, [&]() { useAsFilter(QString ("~"), /* binary */ true); }); connect(regexpAction, &QAction::triggered, this, [&]() { useAsFilter(QString ("/"), /* binary */ false, QString ("/")); }); connect(condFormatAction, &QAction::triggered, this, [&]() { emit editCondFormats(currentIndex().column()); }); connect(nullAction, &QAction::triggered, this, [&]() { setToNull(selectedIndexes()); }); connect(copyAction, &QAction::triggered, this, [&]() { copy(false, false); }); connect(cutAction, &QAction::triggered, this, &ExtendedTableWidget::cut); connect(copyWithHeadersAction, &QAction::triggered, this, [&]() { copy(true, false); }); connect(copyAsSQLAction, &QAction::triggered, this, [&]() { copy(false, true); }); connect(pasteAction, &QAction::triggered, this, [&]() { paste(); }); connect(printAction, &QAction::triggered, this, [&]() { openPrintDialog(); }); // Add spreadsheet shortcuts for selecting entire columns or entire rows. QShortcut* selectColumnShortcut = new QShortcut(QKeySequence("Ctrl+Space"), this); connect(selectColumnShortcut, &QShortcut::activated, this, [this]() { if(!hasFocus() || selectionModel()->selectedIndexes().isEmpty()) return; selectionModel()->select(selectionModel()->selection(), QItemSelectionModel::Select | QItemSelectionModel::Columns); }); QShortcut* selectRowShortcut = new QShortcut(QKeySequence("Shift+Space"), this); connect(selectRowShortcut, &QShortcut::activated, this, [this]() { if(!hasFocus() || selectionModel()->selectedIndexes().isEmpty()) return; selectionModel()->select(selectionModel()->selection(), QItemSelectionModel::Select | QItemSelectionModel::Rows); }); // Set up frozen columns child widget if(m_frozen_table_view) { // Set up widget m_frozen_table_view->setFocusPolicy(Qt::NoFocus); m_frozen_table_view->verticalHeader()->hide(); m_frozen_table_view->setStyleSheet("QTableView { border: none; }" "QTableView::item:selected{ background-color: " + palette().color(QPalette::Active, QPalette::Highlight).name() + "}"); m_frozen_table_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_frozen_table_view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_frozen_table_view->setVerticalScrollMode(verticalScrollMode()); viewport()->stackUnder(m_frozen_table_view); m_tableHeader->stackUnder(m_frozen_table_view); // Keep both widgets in sync connect(horizontalHeader(), &QHeaderView::sectionResized, this, &ExtendedTableWidget::updateSectionWidth); connect(m_frozen_table_view->horizontalHeader(), &QHeaderView::sectionResized, this, &ExtendedTableWidget::updateSectionWidth); connect(verticalHeader(), &QHeaderView::sectionResized, this, &ExtendedTableWidget::updateSectionHeight); connect(m_frozen_table_view->verticalHeader(), &QHeaderView::sectionResized, this, &ExtendedTableWidget::updateSectionHeight); connect(m_frozen_table_view->verticalScrollBar(), &QAbstractSlider::valueChanged, verticalScrollBar(), &QAbstractSlider::setValue); connect(verticalScrollBar(), &QAbstractSlider::valueChanged, m_frozen_table_view->verticalScrollBar(), &QAbstractSlider::setValue); // Forward signals from frozen table view widget to the main table view widget connect(m_frozen_table_view, &ExtendedTableWidget::doubleClicked, this, &ExtendedTableWidget::doubleClicked); connect(m_frozen_table_view->filterHeader(), &FilterTableHeader::sectionClicked, filterHeader(), &FilterTableHeader::sectionClicked); connect(m_frozen_table_view->filterHeader(), &QHeaderView::sectionDoubleClicked, filterHeader(), &QHeaderView::sectionDoubleClicked); connect(m_frozen_table_view->verticalHeader(), &QHeaderView::sectionResized, verticalHeader(), &QHeaderView::sectionResized); connect(m_frozen_table_view->horizontalHeader(), &QHeaderView::customContextMenuRequested, horizontalHeader(), &QHeaderView::customContextMenuRequested); connect(m_frozen_table_view->verticalHeader(), &QHeaderView::customContextMenuRequested, verticalHeader(), &QHeaderView::customContextMenuRequested); connect(m_frozen_table_view, &ExtendedTableWidget::openFileFromDropEvent, this, &ExtendedTableWidget::openFileFromDropEvent); connect(m_frozen_table_view, &ExtendedTableWidget::selectedRowsToBeDeleted, this, &ExtendedTableWidget::selectedRowsToBeDeleted); connect(m_frozen_table_view->filterHeader(), &FilterTableHeader::filterChanged, filterHeader(), &FilterTableHeader::filterChanged); connect(m_frozen_table_view->filterHeader(), &FilterTableHeader::addCondFormat, filterHeader(), &FilterTableHeader::addCondFormat); connect(m_frozen_table_view->filterHeader(), &FilterTableHeader::allCondFormatsCleared, filterHeader(), &FilterTableHeader::allCondFormatsCleared); connect(m_frozen_table_view->filterHeader(), &FilterTableHeader::condFormatsEdited, filterHeader(), &FilterTableHeader::condFormatsEdited); connect(m_frozen_table_view, &ExtendedTableWidget::editCondFormats, this, &ExtendedTableWidget::editCondFormats); connect(m_frozen_table_view, &ExtendedTableWidget::dataAboutToBeEdited, this, &ExtendedTableWidget::dataAboutToBeEdited); connect(m_frozen_table_view, &ExtendedTableWidget::foreignKeyClicked, this, &ExtendedTableWidget::foreignKeyClicked); connect(m_frozen_table_view, &ExtendedTableWidget::currentIndexChanged, this, &ExtendedTableWidget::currentIndexChanged); } #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) && QT_VERSION < QT_VERSION_CHECK(5, 12, 3) // This work arounds QTBUG-73721 and it is applied only for the affected version range. setWordWrap(false); #endif } ExtendedTableWidget::~ExtendedTableWidget() { delete m_frozen_table_view; } void ExtendedTableWidget::setModel(QAbstractItemModel* item_model) { // Set model QTableView::setModel(item_model); // Set up frozen table view widget if(item_model) setFrozenColumns(m_frozen_column_count); else m_frozen_table_view->hide(); } void ExtendedTableWidget::reloadSettings() { // We only get the font here to get its metrics. The actual font for the view is set in the model QFont dataBrowserFont(Settings::getValue("databrowser", "font").toString()); dataBrowserFont.setPointSize(Settings::getValue("databrowser", "fontsize").toInt()); // Set new default row height depending on the font size QFontMetrics fontMetrics(dataBrowserFont); verticalHeader()->setDefaultSectionSize(fontMetrics.height()+10); if(m_frozen_table_view) m_frozen_table_view->reloadSettings(); setWordWrap(Settings::getValue("databrowser", "cell_word_wrap").toBool()); } bool ExtendedTableWidget::copyMimeData(const QModelIndexList& fromIndices, QMimeData* mimeData, const bool withHeaders, const bool inSQL) { QModelIndexList indices = fromIndices; // Remove all indices from hidden columns, because if we don't, we might copy data from hidden columns as well which is very // unintuitive; especially copying the rowid column when selecting all columns of a table is a problem because pasting the data // won't work as expected. QMutableListIterator<QModelIndex> it(indices); while (it.hasNext()) { if (isColumnHidden(it.next().column())) it.remove(); } // Abort if there's nothing to copy if (indices.isEmpty()) return false; SqliteTableModel* m = qobject_cast<SqliteTableModel*>(model()); // Clear internal copy-paste buffer m_buffer.clear(); // If a single cell is selected which contains an image, copy it to the clipboard if (!inSQL && !withHeaders && indices.size() == 1) { QImage img; QVariant varData = m->data(indices.first(), Qt::EditRole); if (img.loadFromData(varData.toByteArray())) { // If it's an image, copy the image data to the clipboard mimeData->setImageData(img); return false; } } // If we got here, a non-image cell was or multiple cells were selected, or copy with headers was requested. // In this case, we copy selected data into internal copy-paste buffer and then // we write a table both in HTML and text formats to the system clipboard. // Copy selected data into internal copy-paste buffer int last_row = indices.first().row(); BufferRow lst; for(int i=0;i<indices.size();i++) { if(indices.at(i).row() != last_row) { m_buffer.push_back(lst); lst.clear(); } lst.push_back(indices.at(i).data(Qt::EditRole).toByteArray()); last_row = indices.at(i).row(); } m_buffer.push_back(lst); // TSV text or SQL QString result; // HTML text QString htmlResult = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">" "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">" "<title></title>"; // The generator-stamp is later used to know whether the data in the system clipboard is still ours. // In that case we will give precedence to our internal copy buffer. QString now = QDateTime::currentDateTime().toString("YYYY-MM-DDTHH:mm:ss.zzz"); m_generatorStamp = QString("<meta name=\"generator\" content=\"%1\"><meta name=\"date\" content=\"%2\">").arg(QApplication::applicationName().toHtmlEscaped(), now); htmlResult.append(m_generatorStamp); // TODO: is this really needed by Excel, since we use <pre> for multi-line cells? htmlResult.append("<style type=\"text/css\">br{mso-data-placement:same-cell;}</style></head><body>" "<table border=1 cellspacing=0 cellpadding=2>"); // Insert the columns in a set, since they could be non-contiguous. std::set<int> colsInIndexes, rowsInIndexes; for(const QModelIndex & idx : qAsConst(indices)) { colsInIndexes.insert(idx.column()); rowsInIndexes.insert(idx.row()); } const QString fieldSepText = "\t"; #ifdef Q_OS_WIN const QString rowSepText = "\r\n"; #else const QString rowSepText = "\n"; #endif int firstColumn = *colsInIndexes.begin(); QString sqlInsertStatement; // Table headers if (withHeaders || inSQL) { if (inSQL) sqlInsertStatement = QString("INSERT INTO %1 (").arg(QString::fromStdString(m->currentTableName().toString())); else htmlResult.append("<tr><th>"); for(int col : colsInIndexes) { QByteArray headerText = model()->headerData(col, Qt::Horizontal, Qt::EditRole).toByteArray(); if (col != firstColumn) { if (inSQL) sqlInsertStatement.append(", "); else { result.append(fieldSepText); htmlResult.append("</th><th>"); } } if (inSQL) sqlInsertStatement.append(sqlb::escapeIdentifier(headerText)); else { result.append(headerText); htmlResult.append(headerText); } } if (inSQL) sqlInsertStatement.append(") VALUES ("); else { result.append(rowSepText); htmlResult.append("</th></tr>"); } } QProgressDialog progress(this); progress.setWindowModality(Qt::ApplicationModal); // Disable context help button on Windows progress.setWindowFlags(progress.windowFlags() & ~Qt::WindowContextHelpButtonHint); progress.setRange(*rowsInIndexes.begin(), *rowsInIndexes.rbegin()); progress.setMinimumDuration(2000); // Iterate over rows x cols checking if the index actually exists when needed, in order // to support non-rectangular selections. for(const int row : rowsInIndexes) { // Beginning of row if (inSQL) result.append(sqlInsertStatement); else htmlResult.append("<tr>"); for(const int column : colsInIndexes) { const QModelIndex index = indices.first().sibling(row, column); const bool isContained = indices.contains(index); if (column != firstColumn) { // Add text separators if (inSQL) result.append(", "); else result.append(fieldSepText); } if(isContained) { QFont font; font.fromString(index.data(Qt::FontRole).toString()); const Qt::Alignment align(index.data(Qt::TextAlignmentRole).toInt()); const QString textAlign(CondFormat::alignmentTexts().at(CondFormat::fromCombinedAlignment(align)).toLower()); htmlResult.append(QString("<td style=\"font-family:'%1';font-size:%2pt;font-style:%3;font-weight: %4;%5 " "background-color:%6;color:%7;text-align:%8\">").arg( font.family().toHtmlEscaped(), // font-family QString::number(font.pointSize()), // font-size font.italic() ? "italic" : "normal", // font-style, font.bold() ? "bold" : "normal", // font-weigth, font.underline() ? " text-decoration: underline;" : "", // text-decoration, index.data(Qt::BackgroundRole).toString(), // background-color index.data(Qt::ForegroundRole).toString(), // color textAlign)); } else { htmlResult.append("<td>"); } QImage img; const QVariant bArrdata = isContained ? index.data(Qt::EditRole) : QVariant(); if (bArrdata.isNull()) { // NULL data: NULL in SQL, empty in HTML or text. if (inSQL) result.append("NULL"); } else if(!m->isBinary(index)) { // Text data QByteArray text = bArrdata.toByteArray(); if (inSQL) { // Escape string only if it isn't a number. switch(bArrdata.type()) { case QVariant::Double: case QVariant::Int: case QVariant::LongLong: case QVariant::UInt: case QVariant::ULongLong: result.append(text); break; default: result.append(sqlb::escapeString(text)); } } else { result.append(text); // Table cell data: text if (text.contains('\n') || text.contains('\t')) htmlResult.append(QString("<pre>%1</pre>").arg(QString(text).toHtmlEscaped())); else htmlResult.append(QString(text).toHtmlEscaped()); } } else if (inSQL) { // Table cell data: binary in SQL. Save as BLOB literal. result.append(QString("X'%1'").arg(QString(bArrdata.toByteArray().toHex()))); } else if (img.loadFromData(bArrdata.toByteArray())) { // Table cell data: image. Store it as an embedded image in HTML QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); img.save(&buffer, "PNG"); buffer.close(); htmlResult.append(QString("<img src=\"data:image/png;base64,%1\" alt=\"Image\">") .arg(QString(ba.toBase64()))); result.append(index.data(Qt::DisplayRole).toByteArray()); } // End of column // Add HTML cell terminator htmlResult.append("</td>"); } // End of row if (inSQL) result.append(");"); else htmlResult.append("</tr>"); result.append(rowSepText); progress.setValue(row); // Abort the operation if the user pressed ESC key or Cancel button if (progress.wasCanceled()) { return false; } } if (!inSQL) { htmlResult.append("</table></body></html>"); mimeData->setHtml(htmlResult); } // Single cells should only contain the value, not an ending row separator. if (indices.size() == 1) { result.resize(result.size() - rowSepText.size()); } mimeData->setText(result); return true; } void ExtendedTableWidget::copy(const bool withHeaders, const bool inSQL ) { QMimeData *mimeData = new QMimeData; copyMimeData(selectionModel()->selectedIndexes(), mimeData, withHeaders, inSQL); qApp->clipboard()->setMimeData(mimeData); } void ExtendedTableWidget::paste() { // Get list of selected items QItemSelectionModel* selection = selectionModel(); QModelIndexList indices = selection->selectedIndexes(); // Abort if there's nowhere to paste if(indices.isEmpty()) return; SqliteTableModel* m = qobject_cast<SqliteTableModel*>(model()); // We're also checking for system clipboard data first. Only if the data in the system clipboard is not ours, we use the system // clipboard, otherwise we prefer the internal buffer. That's because the data in the internal buffer is easier to parse and more // accurate, too. However, if we always preferred the internal copy-paste buffer there would be no way to copy data from other // applications in here once the internal buffer has been filled. // If clipboard contains an image and no text, just insert the image const QMimeData* mimeClipboard = qApp->clipboard()->mimeData(); if (mimeClipboard->hasImage() && !mimeClipboard->hasText()) { QImage img = qApp->clipboard()->image(); QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); img.save(&buffer, "PNG"); // We're always converting the image format to PNG here. TODO: Is that correct? buffer.close(); m->setTypedData(indices.first(), /* isBlob = */ !isTextOnly(ba), ba); return; } // Get the clipboard text QString clipboard = qApp->clipboard()->text(); // If data in system clipboard is ours and the internal copy-paste buffer is filled, use the internal buffer; otherwise parse the // system clipboard contents (case for data copied by other application). std::vector<BufferRow> clipboardTable; std::vector<BufferRow>* source; if(mimeClipboard->hasHtml() && mimeClipboard->html().contains(m_generatorStamp) && !m_buffer.empty()) { source = &m_buffer; } else { clipboardTable = parseClipboard(clipboard); source = &clipboardTable; } // Stop here if there's nothing to paste if(!source->size()) return; // Starting from assumption that selection is rectangular, and then first index is upper-left corner and last is lower-right. int rows = static_cast<int>(source->size()); int columns = static_cast<int>(source->front().size()); int firstRow = indices.front().row(); int firstColumn = indices.front().column(); int selectedRows = indices.back().row() - firstRow + 1; int selectedColumns = indices.back().column() - firstColumn + 1; // If last row and column are after table size, clamp it int lastRow = qMin(firstRow + rows - 1, m->rowCount() - 1); int lastColumn = qMin(firstColumn + columns - 1, m->columnCount() - 1); // Special case: if there is only one cell of data to be pasted, paste it into all selected fields if(rows == 1 && columns == 1) { QByteArray bArrdata = source->front().front(); for(int row=firstRow;row<firstRow+selectedRows;row++) { for(int column=firstColumn;column<firstColumn+selectedColumns;column++) m->setTypedData(m->index(row, column), !isTextOnly(bArrdata), bArrdata); } return; } // If more than one cell was selected, check if the selection matches the cliboard dimensions if(selectedRows != rows || selectedColumns != columns) { // Ask user if they are sure about this if(QMessageBox::question(this, QApplication::applicationName(), tr("The content of the clipboard is bigger than the range selected.\nDo you want to insert it anyway?"), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { // If the user doesn't want to paste the clipboard data anymore, stop now return; } } // If we get here, we can definitely start pasting: either the ranges match in their size or the user agreed to paste anyway // Copy the data cell by cell and as-is from the source buffer to the table int row = firstRow; for(const auto& source_row : *source) { int column = firstColumn; for(const QByteArray& source_cell : source_row) { m->setData(m->index(row, column), source_cell); column++; if (column > lastColumn) break; } row++; if (row > lastRow) break; } } void ExtendedTableWidget::cut() { const QModelIndexList& indices = selectionModel()->selectedIndexes(); SqliteTableModel* m = qobject_cast<SqliteTableModel*>(model()); sqlb::TablePtr currentTable = m->db().getTableByName(m->currentTableName()); copy(false, false); // Check if the column in the selection has a NOT NULL constraint, then update with an empty string, else with NULL if(currentTable) { for(const QModelIndex& index : indices) { // Do not process rowid column if(index.column() != 0) { const size_t indexField = static_cast<size_t>(index.column()-1); const sqlb::Field& field = currentTable->fields.at(indexField); const QVariant newValue = field.notnull() ? QVariant("") : QVariant(); // Update aborting in case of any error (to avoid repetitive errors like "Database is locked") if(!model()->setData(index, newValue)) return; } } } } void ExtendedTableWidget::useAsFilter(const QString& filterOperator, bool binary, const QString& operatorSuffix) { QModelIndex index = selectionModel()->currentIndex(); SqliteTableModel* m = qobject_cast<SqliteTableModel*>(model()); // Abort if there's nothing to filter if (!index.isValid() || !selectionModel()->hasSelection() || m->isBinary(index)) return; QVariant bArrdata = model()->data(index, Qt::EditRole); QString value; if (bArrdata.isNull()) value = "NULL"; else if (bArrdata.toString().isEmpty()) value = "''"; else value = bArrdata.toString(); // When Containing filter is requested (empty operator) and the value starts with // an operator character, the character is escaped. if (filterOperator.isEmpty()) value.replace(QRegularExpression("^(<|>|=|/)"), Settings::getValue("databrowser", "filter_escape").toString() + QString("\\1")); // If binary operator, the cell data is used as first value and // the second value must be added by the user. size_t column = static_cast<size_t>(index.column()); if (binary) m_tableHeader->setFilter(column, value + filterOperator); else m_tableHeader->setFilter(column, filterOperator + value + operatorSuffix); m_tableHeader->setFocusColumn(column); } void ExtendedTableWidget::duplicateUpperCell() { const QModelIndex& currentIndex = selectionModel()->currentIndex(); QModelIndex upperIndex = currentIndex.sibling(currentIndex.row() - 1, currentIndex.column()); if (upperIndex.isValid()) { SqliteTableModel* m = qobject_cast<SqliteTableModel*>(model()); // When the data is binary, just copy it, since it cannot be edited inline. if (m->isBinary(upperIndex)) m->setData(currentIndex, m->data(upperIndex, Qt::EditRole), Qt::EditRole); else { // Open the inline editor and set the value (this mimics the behaviour of LibreOffice Calc) edit(currentIndex); QLineEdit* editor = qobject_cast<QLineEdit*>(indexWidget(currentIndex)); editor->setText(upperIndex.data().toString()); } } } void ExtendedTableWidget::keyPressEvent(QKeyEvent* event) { // Call a custom copy method when Ctrl-C is pressed if(event->matches(QKeySequence::Copy)) { copy(false, false); return; } else if(event->matches(QKeySequence::Cut)) { // Call a custom cut method when Ctrl-X is pressed cut(); } else if(event->matches(QKeySequence::Paste)) { // Call a custom paste method when Ctrl-V is pressed paste(); } else if(event->matches(QKeySequence::Print)) { openPrintDialog(); } else if(event->modifiers().testFlag(Qt::ControlModifier) && event->modifiers().testFlag(Qt::ShiftModifier) && (event->key() == Qt::Key_C)) { // Call copy with headers when Ctrl-Shift-C is pressed copy(true, false); } else if(event->modifiers().testFlag(Qt::ControlModifier) && event->modifiers().testFlag(Qt::AltModifier) && (event->key() == Qt::Key_C)) { // Call copy in SQL format when Ctrl-Alt-C is pressed copy(false, true); } else if(event->modifiers().testFlag(Qt::ControlModifier) && (event->key() == Qt::Key_Apostrophe)) { // Call duplicateUpperCell when Ctrl-' is pressed (this is used by spreadsheets for "Copy Formula from Cell Above") duplicateUpperCell(); } else if(event->key() == Qt::Key_Tab && hasFocus() && selectedIndexes().count() == 1 && selectedIndexes().at(0).row() == model()->rowCount()-1 && selectedIndexes().at(0).column() == model()->columnCount()-1) { // If the Tab key was pressed while the focus was on the last cell of the last row insert a new row automatically model()->insertRow(model()->rowCount()); } else if ((event->key() == Qt::Key_Delete) || (event->key() == Qt::Key_Backspace)) { // Check if entire rows are selected. We call the selectedRows() method here not only for simplicity reasons but also because it distinguishes between // "an entire row is selected" and "all cells of a row are selected", the former is e.g. the case when the row number is clicked, the latter when all cells // are selected manually. This is an important distinction (especially when a table has only one column!) to match the users' expectations. Also never // delete records when the backspace key was pressed. if(event->key() == Qt::Key_Delete && selectionModel()->selectedRows().size()) { // At least on entire row is selected. Because we don't allow completely arbitrary selections (at least at the moment) but only block selections, // this means that only entire entire rows are selected. If an entire row is (or multiple entire rows are) selected, we delete that record instead // of deleting only the cell contents. emit selectedRowsToBeDeleted(); } else { // No entire row is selected. So just set the selected cells to null or empty string depending on the modifier keys if(event->modifiers().testFlag(Qt::AltModifier)) { // When pressing Alt+Delete set the value to NULL setToNull(selectedIndexes()); } else { // When pressing Delete only set the value to empty string for(const QModelIndex& index : selectedIndexes()) { if(!model()->setData(index, "")) return; } } } } else if(event->modifiers().testFlag(Qt::ControlModifier) && (event->key() == Qt::Key_PageUp || event->key() == Qt::Key_PageDown)) { // When pressing Ctrl + Page up/down send a signal indicating the user wants to change the current table emit switchTable(event->key() == Qt::Key_PageDown); return; } // Discoverability of Ctrl+Shift+Click to follow foreign keys or URLs if(event->modifiers().testFlag(Qt::ControlModifier) && event->modifiers().testFlag(Qt::ShiftModifier)) QApplication::setOverrideCursor(Qt::PointingHandCursor); // This prevents the current selection from being changed when pressing tab to move to the next filter. Note that this is in an 'if' condition, // not in an 'else if' because this way, when the tab key was pressed and the focus was on the last cell, a new row is inserted and then the tab // key press is processed a second time to move the cursor as well if((event->key() != Qt::Key_Tab && event->key() != Qt::Key_Backtab) || hasFocus()) QTableView::keyPressEvent(event); } void ExtendedTableWidget::keyReleaseEvent(QKeyEvent* event) { // Restore the PointingHandCursor override if(!event->modifiers().testFlag(Qt::ControlModifier) || !event->modifiers().testFlag(Qt::ShiftModifier)) QApplication::restoreOverrideCursor(); QTableView::keyReleaseEvent(event); } void ExtendedTableWidget::updateGeometries() { // Call the parent implementation first - it does most of the actual logic QTableView::updateGeometries(); // Update frozen columns view too if(m_frozen_table_view) m_frozen_table_view->updateGeometries(); // Check if a model has already been set yet if(model()) { // If so and if it is a SqliteTableModel and if the parent implementation of this method decided that a scrollbar is needed, update its maximum value SqliteTableModel* m = qobject_cast<SqliteTableModel*>(model()); if(m && verticalScrollBar()->maximum()) { verticalScrollBar()->setMaximum(m->rowCount() - numVisibleRows() + 1); if(m_frozen_table_view) m_frozen_table_view->verticalScrollBar()->setMaximum(verticalScrollBar()->maximum()); } } } void ExtendedTableWidget::vscrollbarChanged(int value) { // Cancel if there is no model set yet - this shouldn't happen (because without a model there should be no scrollbar) but just to be sure... if(!model()) return; // Fetch more data from the DB if necessary |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |