// Table factory QTableView* MakeTableView(QAbstractItemModel* model, bool sortingEnabled = true, uint32_t modelSortColumn = 0) { class MyTable : public QTableView { public: QStyleOptionViewItem viewOptions() const override { QStyleOptionViewItem option = QTableView::viewOptions(); option.decorationAlignment = Qt::AlignHCenter | Qt::AlignCenter; option.decorationPosition = QStyleOptionViewItem::Top; return option; } void mouseMoveEvent(QMouseEvent* event) override { QModelIndex index = indexAt(event->pos()); if (index.isValid()) { QVariant data = model()->data(index, PlayerTableModel::CursorRole); Qt::CursorShape shape = Qt::ArrowCursor; if (!data.isNull()) { shape = Qt::CursorShape(data.toInt()); } setCursor(shape); } QTableView::mouseMoveEvent(event); } }; QTableView* tableView = new MyTable(); tableView->setModel(model); tableView->setSortingEnabled(sortingEnabled); if (sortingEnabled) { tableView->sortByColumn(FindColumn(model, modelSortColumn)); } tableView->verticalHeader()->hide(); tableView->setAlternatingRowColors(true); tableView->verticalHeader()->setDefaultSectionSize(15); tableView->resizeColumnsToContents(); tableView->horizontalHeader()->setStretchLastSection(true); tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->setSelectionMode(QAbstractItemView::SingleSelection); tableView->setFocusPolicy(Qt::StrongFocus); // enable mouse tracking tableView->setMouseTracking(true); tableView->viewport()->setMouseTracking(true); tableView->installEventFilter(this); tableView->viewport()->installEventFilter(this); return tableView; }
void tst_QItemDelegate::QTBUG4435_keepSelectionOnCheck() { QStandardItemModel model(3, 1); for (int i = 0; i < 3; ++i) { QStandardItem *item = new QStandardItem(QLatin1String("Item ") + QString::number(i)); item->setCheckable(true); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); model.setItem(i, item); } QTableView view; view.setModel(&model); view.setItemDelegate(new TestItemDelegate); view.show(); view.selectAll(); QVERIFY(QTest::qWaitForWindowExposed(&view)); QStyleOptionViewItem option; option.rect = view.visualRect(model.index(0, 0)); // mimic QStyledItemDelegate::initStyleOption logic option.features = QStyleOptionViewItem::HasDisplay | QStyleOptionViewItem::HasCheckIndicator; option.checkState = Qt::CheckState(model.index(0, 0).data(Qt::CheckStateRole).toInt()); const int checkMargin = qApp->style()->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, 0) + 1; QPoint pos = qApp->style()->subElementRect(QStyle::SE_ViewItemCheckIndicator, &option, 0).center() + QPoint(checkMargin, 0); QTest::mouseClick(view.viewport(), Qt::LeftButton, Qt::ControlModifier, pos); QTRY_VERIFY(view.selectionModel()->isColumnSelected(0, QModelIndex())); QCOMPARE(model.item(0)->checkState(), Qt::Checked); }
void MainWindow::createSongsTable(int size) { QTableView * songs = ui->tvSongs; delete songs->model(); delete songs->selectionModel(); QStandardItemModel *model = new QStandardItemModel(size, 3, songs); QItemSelectionModel *selections = new QItemSelectionModel(model); songs->setModel(model); songs->setSelectionModel(selections); songs->horizontalHeader()->setSectionsMovable(true); songs->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); songs->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); songs->verticalHeader()->setSectionsMovable(false); songs->verticalHeader()->setVisible(false); songs->setSelectionBehavior( QAbstractItemView::SelectRows ); songs->setSelectionMode( QAbstractItemView::SingleSelection ); songs->setContextMenuPolicy(Qt::CustomContextMenu); // Set StaticContents to enable minimal repaints on resizes. songs->viewport()->setAttribute(Qt::WA_StaticContents); model->setHorizontalHeaderItem(0, new QStandardItem(tr("Artist"))); model->setHorizontalHeaderItem(1, new QStandardItem(tr("Title"))); model->setHorizontalHeaderItem(2, new QStandardItem(tr("Length"))); }
int main(int argc, char *argv[]) { Q_INIT_RESOURCE(interview); QApplication app(argc, argv); QSplitter page; QAbstractItemModel *data = new Model(1000, 10, &page); QItemSelectionModel *selections = new QItemSelectionModel(data); QTableView *table = new QTableView; table->setModel(data); table->setSelectionModel(selections); table->horizontalHeader()->setMovable(true); table->verticalHeader()->setMovable(true); // Set StaticContents to enable minimal repaints on resizes. table->viewport()->setAttribute(Qt::WA_StaticContents); page.addWidget(table); QTreeView *tree = new QTreeView; tree->setModel(data); tree->setSelectionModel(selections); tree->setUniformRowHeights(true); tree->header()->setStretchLastSection(false); tree->viewport()->setAttribute(Qt::WA_StaticContents); // Disable the focus rect to get minimal repaints when scrolling on Mac. tree->setAttribute(Qt::WA_MacShowFocusRect, false); page.addWidget(tree); QListView *list = new QListView; list->setModel(data); list->setSelectionModel(selections); list->setViewMode(QListView::IconMode); list->setSelectionMode(QAbstractItemView::ExtendedSelection); list->setAlternatingRowColors(false); list->viewport()->setAttribute(Qt::WA_StaticContents); list->setAttribute(Qt::WA_MacShowFocusRect, false); page.addWidget(list); page.setWindowIcon(QPixmap(":/images/interview.png")); page.setWindowTitle("Interview"); page.show(); return app.exec(); }
TransactionView::TransactionView(QWidget *parent) : QWidget(parent), model(0), transactionProxyModel(0), transactionView(0) { setContentsMargins(0,0,0,0); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->setContentsMargins(0,0,0,0); #ifdef Q_OS_MAC hlayout->setSpacing(5); hlayout->addSpacing(26); #else hlayout->setSpacing(0); hlayout->addSpacing(23); #endif // Build filter row dateWidget = new QComboBox(this); #ifdef Q_OS_MAC dateWidget->setFixedWidth(151); #else dateWidget->setFixedWidth(150); #endif dateWidget->addItem(tr("All"), All); dateWidget->addItem(tr("Today"), Today); dateWidget->addItem(tr("This week"), ThisWeek); dateWidget->addItem(tr("This month"), ThisMonth); dateWidget->addItem(tr("Last month"), LastMonth); dateWidget->addItem(tr("This year"), ThisYear); dateWidget->addItem(tr("Range..."), Range); hlayout->addWidget(dateWidget); typeWidget = new QComboBox(this); #ifdef Q_OS_MAC typeWidget->setFixedWidth(121); #else typeWidget->setFixedWidth(120); #endif typeWidget->addItem(tr("All"), TransactionFilterProxy::ALL_TYPES); typeWidget->addItem(tr("Received with"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) | TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther)); typeWidget->addItem(tr("Sent to"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) | TransactionFilterProxy::TYPE(TransactionRecord::SendToOther)); typeWidget->addItem(tr("To yourself"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf)); typeWidget->addItem(tr("Interest"), TransactionFilterProxy::TYPE(TransactionRecord::Generated)); typeWidget->addItem(tr("Other"), TransactionFilterProxy::TYPE(TransactionRecord::Other)); hlayout->addWidget(typeWidget); addressWidget = new QLineEdit(this); #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ addressWidget->setPlaceholderText(tr("Enter address or label to search")); #endif hlayout->addWidget(addressWidget); amountWidget = new QLineEdit(this); #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ amountWidget->setPlaceholderText(tr("Min amount")); #endif amountWidget->setFixedWidth(100); amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this)); hlayout->addWidget(amountWidget); QVBoxLayout *vlayout = new QVBoxLayout(this); vlayout->setContentsMargins(0,0,0,0); vlayout->setSpacing(0); QTableView *view = new QTableView(this); view->setFont(qFont); view->setMouseTracking(true); view->viewport()->setAttribute(Qt::WA_Hover, true); view->horizontalHeader()->setHighlightSections(false); vlayout->addLayout(hlayout); vlayout->addWidget(createDateRangeWidget()); vlayout->addWidget(view); vlayout->setSpacing(0); int width = view->verticalScrollBar()->sizeHint().width(); // Cover scroll bar width with spacing #ifdef Q_OS_MAC hlayout->addSpacing(width+2); #else hlayout->addSpacing(width); #endif // Always show scroll bar view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); view->setTabKeyNavigation(false); view->setContextMenuPolicy(Qt::CustomContextMenu); transactionView = view; totalWidget = new QLabel(this); totalWidget->setFont(qFont); totalWidget->setAlignment(Qt::AlignBottom | Qt::AlignRight); totalWidget->setLayoutDirection(Qt::RightToLeft); totalWidget->setFixedHeight(27); totalWidget->setFixedWidth(300); totalWidget->setText(tr("Total: ")); totalWidget->setToolTip(tr("Total of displayed transactions.\nHidden decimals are not totaled.")); vlayout->addWidget(totalWidget); // Actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); QAction *copyTxIDAction = new QAction(tr("Copy transaction ID"), this); QAction *editLabelAction = new QAction(tr("Edit label"), this); QAction *showDetailsAction = new QAction(tr("Show transaction details"), this); contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTxIDAction); contextMenu->addAction(editLabelAction); contextMenu->addAction(showDetailsAction); // Connect actions connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int))); connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int))); connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString))); connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString))); connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex))); connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID())); connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel())); connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails())); }
void Button::placeButton() { QTableView* table = qobject_cast<QTableView*>(this->parent()); if (!table) { setVisible(false); return ; } if (_point.isNull()) { QSize s = table->viewport()->size(); //qDebug() << s; _point = QPoint(s.width(),s.height()); } QAbstractItemModel* model = table->model(); if (!model) return; int n,m,bsize1,bsize2,offset1,offset2,point1,point2; getSizes(table,model,&m,&n,&bsize1,&bsize2,&point1,&point2,&offset1,&offset2); int coord1; int coord2 = 0; int sizes[m]; if (_orientation == Qt::Horizontal) { for (int i=0;i<m;i++) sizes[i] = table->columnWidth(i); for (int i=0;i<n;i++) coord2 += table->rowHeight(i); } else { for (int i=0;i<m;i++) sizes[i] = table->rowHeight(i); for (int i=0;i<n;i++) coord2 += table->columnWidth(i); } if (_type == InsertRemove::Insert) nearestBorder(_policy,point1+offset1,sizes,m,&_modelIndex,&coord1); else // _type == InsertRemove::Remove nearestMiddle(_policy,point1+offset1,sizes,m,&_modelIndex,&coord1); coord1 -= bsize1 / 2; QSize vp = usefulWidgetSize(table); QPoint sh = table->viewport()->mapToParent(QPoint(0,0)); //насколько viewport меньше table if (_orientation == Qt::Horizontal) { if (coord2 - offset2 + bsize2 + sh.y() > vp.height()) coord2 = vp.height() - bsize2 + offset2 - sh.y(); } else { if (coord2 - offset2 + bsize2 + sh.x() > vp.width()) coord2 = vp.width() - bsize2 + offset2 - sh.x(); } if (_orientation == Qt::Horizontal) { QPoint p = table->viewport()->mapToParent(QPoint(coord1 - offset1,coord2 - offset2)); setGeometry(QRect(p,size())); } else { QPoint p = table->viewport()->mapToParent(QPoint(coord2 - offset2,coord1 - offset1)); setGeometry(QRect(p,size())); } if (_type == InsertRemove::Insert) { setVisible(_modelIndex>=0); } else { setVisible((_policy & InsertRemove::RemoveAllowed) && (_modelIndex>-1)); } }
int main(int argc, char *argv[]) { QApplication app(argc, argv); ToDoListModel model; // Labels with totals QLabel * lcEffort = new QLabel; TotalEstimateLabel * lEffort = new TotalEstimateLabel; lcEffort->setText("Total Effort"); QObject::connect(&model, SIGNAL(totalEffortChanged(int)), lEffort, SLOT(setTotalEstimate(int))); QLabel * lcEstimated = new QLabel(); TotalEstimateLabel * lEstimated = new TotalEstimateLabel(); lcEstimated->setText("Estimated Effort"); QObject::connect(&model, SIGNAL(totalEstimateChanged(int)), lEstimated, SLOT(setTotalEstimate(int))); QFormLayout * form1 = new QFormLayout; form1->addRow(lcEffort, lEffort); form1->addRow(lcEstimated, lEstimated); // Table with tasks QTableView *table = new QTableView; // TODO enable drag and drop for moving cells table->setDragEnabled(true); table->viewport()->setAcceptDrops(true); table->setDropIndicatorShown(true); table->setDragDropMode(QAbstractItemView::InternalMove); // Init model after the signal is set. QList<ToDoItem> tasks; for (int row = 0; row < 100; ++row) { ToDoItem ti; ti.name = QString("Task %0").arg(row + 1); ti.estimated_minutes = row + 1; ti.was_done = false; tasks.append(ti); } model.appendTasks(tasks); // NOTE: add now the model, otherwise the table does not show data. table->setModel(&model); // Add widgets to the main layout QVBoxLayout *layout = new QVBoxLayout; layout->addLayout(form1); layout->addWidget(table); // Create main window QWidget window; window.setLayout(layout); window.setWindowTitle("Lazy GUI Chooser - QT"); window.show(); return app.exec(); }