コード例 #1
0
void CMakeBuildSettingsWidget::updateSelection(const QModelIndex &current, const QModelIndex &previous)
{
    Q_UNUSED(previous);

    m_editButton->setEnabled(current.isValid() && current.flags().testFlag(Qt::ItemIsEditable));
    m_unsetButton->setEnabled(current.isValid() && current.flags().testFlag(Qt::ItemIsSelectable));
}
コード例 #2
0
ファイル: ctkTreeComboBox.cpp プロジェクト: 151706061/CTK
// -------------------------------------------------------------------------
bool ctkTreeComboBox::eventFilter(QObject* object, QEvent* _event)
{
  Q_D(ctkTreeComboBox);
  Q_UNUSED(object);
  bool res = false;
  d->SendCurrentItem = false;
  switch (_event->type())
    {
    default:
      break;
    case QEvent::ShortcutOverride:
      switch (static_cast<QKeyEvent*>(_event)->key())
        {
        case Qt::Key_Enter:
        case Qt::Key_Return:
        case Qt::Key_Select:
          d->SendCurrentItem = true;
          break;
        default:
          break;
        }
      break;
    case QEvent::MouseButtonRelease:
      QMouseEvent* mouseEvent = dynamic_cast<QMouseEvent*>(_event); 
      QModelIndex index = this->view()->indexAt(mouseEvent->pos());
      // do we click the branch (+ or -) or the item itself ?
      if (this->view()->model()->hasChildren(index) && 
          (index.flags() & Qt::ItemIsSelectable) &&
          !this->view()->visualRect(index).contains(mouseEvent->pos()))
        {//qDebug() << "Set skip on";
        // if the branch is clicked, then we don't want to close the 
        // popup. (we don't want to select the item, just expand it.)
        // of course, all that doesn't apply with unselectable items, as
        // they won't close the popup.
        d->SkipNextHide = true;
        }

      // we want to get rid of an odd behavior. 
      // If the user highlight a selectable item and then 
      // click on the branch of an unselectable item while keeping the 
      // previous selection. The popup would be normally closed in that
      // case. We don't want that.
      if ( this->view()->model()->hasChildren(index) && 
           !(index.flags() & Qt::ItemIsSelectable) &&         
           !this->view()->visualRect(index).contains(mouseEvent->pos()))
        {//qDebug() << "eat";
        // eat the event, don't go to the QComboBox event filters.
        res = true;
        }

      d->SendCurrentItem = this->view()->rect().contains(mouseEvent->pos()) &&
        this->view()->currentIndex().isValid() &&
        (this->view()->currentIndex().flags() & Qt::ItemIsEnabled) &&
        (this->view()->currentIndex().flags() & Qt::ItemIsSelectable);
      break;
    }
  return res;
}
コード例 #3
0
void MouseProfileDialog::updateGesturesActions()
{
	disconnect(m_ui->stepsViewWidget->getSourceModel(), &QStandardItemModel::dataChanged, this, &MouseProfileDialog::saveGesture);

	const QModelIndex index(m_ui->gesturesViewWidget->currentIndex().sibling(m_ui->gesturesViewWidget->currentIndex().row(), 0));
	const bool isGesture(index.flags().testFlag(Qt::ItemNeverHasChildren));

	m_ui->gesturesViewWidget->setCurrentIndex(index.sibling(index.row(), 0));
	m_ui->stepsViewWidget->getSourceModel()->removeRows(0, m_ui->stepsViewWidget->getSourceModel()->rowCount());
	m_ui->addGestureButton->setEnabled(index.isValid());
	m_ui->removeGestureButton->setEnabled(isGesture);

	if (isGesture)
	{
		const QStringList steps(index.sibling(index.row(), 2).data(Qt::DisplayRole).toString().split(QLatin1String(", ")));

		for (int i = 0; i < steps.count(); ++i)
		{
			QStandardItem *item(new QStandardItem(steps.at(i)));
			item->setFlags(item->flags() | Qt::ItemNeverHasChildren);

			m_ui->stepsViewWidget->getSourceModel()->appendRow(item);
		}
	}

	updateStepsActions();

	connect(m_ui->stepsViewWidget->getSourceModel(), &QStandardItemModel::dataChanged, this, &MouseProfileDialog::saveGesture);
}
コード例 #4
0
ファイル: htmldelegate.cpp プロジェクト: KDE/kate
void SPHtmlDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QStyleOptionViewItemV4 options = option;
    initStyleOption(&options, index);

    QTextDocument doc;
    //doc.setDocumentMargin(0);
    doc.setHtml(index.data().toString());

    painter->save();
    options.text = QString();  // clear old text
    options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter, options.widget);

    // draw area
    QRect clip = options.widget->style()->subElementRect(QStyle::SE_ItemViewItemText, &options);
    QFontMetrics metrics(options.font);
    if (index.flags() == Qt::NoItemFlags) {
        painter->setBrush(QBrush(QWidget().palette().color(QPalette::Base)));
        painter->setPen(QWidget().palette().color(QPalette::Base));
        painter->drawRect(QRect(clip.topLeft() - QPoint(20, metrics.descent()), clip.bottomRight()));
        painter->translate(clip.topLeft() - QPoint(20, metrics.descent()));
    }
    else {
        painter->translate(clip.topLeft() - QPoint(0, metrics.descent()));
    }
    QAbstractTextDocumentLayout::PaintContext pcontext;
    doc.documentLayout()->draw(painter, pcontext);

    painter->restore();
}
コード例 #5
0
bool ColorDelegate::editorEvent(QEvent* event,
                                QAbstractItemModel* model,
                                const QStyleOptionViewItem& option,
                                const QModelIndex& index)
{

    if ( event->type() == QEvent::MouseButtonRelease && index.data().canConvert<QColor>())
    {
        QMouseEvent* mouse_event = static_cast<QMouseEvent*>(event);

        if ( mouse_event->button() == Qt::LeftButton &&
            ( index.flags() & Qt::ItemIsEditable) )
        {
            ColorDialog *editor = new ColorDialog(const_cast<QWidget*>(option.widget));
            connect(this, &QObject::destroyed, editor, &QObject::deleteLater);
            editor->setMinimumSize(editor->sizeHint());
            auto original_color = index.data().value<QColor>();
            editor->setColor(original_color);
            auto set_color = [model, index](const QColor& color){
                model->setData(index, QVariant(color));
            };
            connect(editor, &ColorDialog::colorSelected, this, set_color);
            editor->show();
        }

        return true;
    }

    return QAbstractItemDelegate::editorEvent(event, model, option, index);
}
コード例 #6
0
void ContentBlockingDialog::updateProfilesActions()
{
	const QModelIndex index(m_ui->profilesViewWidget->currentIndex().sibling(m_ui->profilesViewWidget->currentIndex().row(), 0));

	m_ui->editProfileButton->setEnabled(index.isValid() && index.flags().testFlag(Qt::ItemNeverHasChildren));
	m_ui->updateProfileButton->setEnabled(index.isValid() && index.data(Qt::UserRole + 1).toUrl().isValid());
}
コード例 #7
0
ファイル: qmenuview.cpp プロジェクト: ianorlin/qlipper
//! Puts all of the children of parent into menu
void QMenuView::createMenu(const QModelIndex &parent, QMenu *parentMenu, QMenu *menu)
{
	if (! menu)
	{
		QIcon icon = qvariant_cast<QIcon>(parent.data(Qt::DecorationRole));

		QVariant v;
		v.setValue(parent);

		menu = new QMenu(parent.data().toString(), this);
		menu->setIcon(icon);
		parentMenu->addMenu(menu);
		menu->menuAction()->setData(v);
		menu->setEnabled(parent.flags().testFlag(Qt::ItemIsEnabled));

		connect(menu, SIGNAL(aboutToShow()), d.data(), SLOT(aboutToShow()));

		return;
	}

	int end = d->m_model->rowCount(parent);
	for (int i = 0; i < end; ++i)
	{
		QModelIndex idx = d->m_model->index(i, 0, parent);
		if (d->m_model->hasChildren(idx))
		{
			createMenu(idx, menu);
		}
		else
		{
			menu->addAction(d->makeAction(idx));
		}
	}
}
コード例 #8
0
Qt::ItemFlags AggregatedPropertyModel::flags(const QModelIndex& index) const
{
  const QModelIndex sourceIndex = mapToSource(index);
  if (!sourceIndex.isValid())
    return QAbstractTableModel::flags(QModelIndex());

  return sourceIndex.flags();
}
コード例 #9
0
ファイル: soundthemeselector.cpp プロジェクト: Anderty/qutim
void SoundThemeSelector::onClicked(const QModelIndex &index)
{
	if (index.column() != 1 || !(index.flags() & Qt::ItemIsEnabled))
		return;

	SoundTheme theme =  Sound::theme(ui->themeSelector->currentText());
	theme.play(static_cast<Notification::Type>(index.row()));
}
コード例 #10
0
void TableView::mousePressEvent(QMouseEvent *event)
{
	QModelIndex index = indexAt(event->pos());

	if (index.flags() & Qt::ItemIsEditable)
		edit(index);
	else
		QTableView::mousePressEvent(event);
}
コード例 #11
0
ファイル: sourcetreeview.cpp プロジェクト: ubertaco/tomahawk
void
SourceTreeView::onItemActivated( const QModelIndex& index )
{
    if ( !index.isValid() || !index.flags().testFlag( Qt::ItemIsEnabled ) )
        return;

    SourceTreeItem* item = itemFromIndex< SourceTreeItem >( index );
    item->activate();
}
コード例 #12
0
void CommandView::goClicked(const QModelIndex &index)
{
    if (index.flags() & Qt::ItemIsSelectable)
    {
        QString commandName = this->model()->data(index, Qt::UserRole).toString();
        if (commandName.isEmpty())
            return;
        changedCommand(commandName);
    }
}
コード例 #13
0
ファイル: playlistview.cpp プロジェクト: Gu1/Clementine
QList<int> PlaylistView::GetEditableColumns() {
  QList<int> columns;
  QHeaderView* h = header();
  for (int col = 0; col < h->count(); col++) {
    if (h->isSectionHidden(col)) continue;
    QModelIndex index = model()->index(0, col);
    if (index.flags() & Qt::ItemIsEditable) columns << h->visualIndex(col);
  }
  qSort(columns);
  return columns;
}
コード例 #14
0
static gboolean
filter_disabled_items(GtkTreeModel *model, GtkTreeIter *iter, G_GNUC_UNUSED gpointer data)
{
    QModelIndex idx;
    if (GTK_IS_Q_TREE_MODEL(model))
        idx = gtk_q_tree_model_get_source_idx(GTK_Q_TREE_MODEL(model), iter);

    if (idx.isValid()) {
        return idx.flags() & Qt::ItemIsEnabled ? TRUE : FALSE;
    }
    return FALSE;
}
コード例 #15
0
ファイル: fasto_text_view.cpp プロジェクト: mdvx/fastonosql
void FastoTextView::textChange() {
  if (editor_->childCount() != 1) {
    save_change_button_->setEnabled(false);
    return;
  }

  QModelIndex index = editor_->selectedItem(1);  // eValue
  bool isEnabled = !editor_->isReadOnly() && index.isValid() && (index.flags() & Qt::ItemIsEditable) &&
                   index.data() != editor_->text().simplified();

  save_change_button_->setEnabled(isEnabled);
}
コード例 #16
0
QColor QmlConsoleItemDelegate::drawBackground(QPainter *painter, const QRect &rect,
                                              const QModelIndex &index,
                                              bool selected) const
{
    painter->save();
    ConsoleItem::ItemType itemType = (ConsoleItem::ItemType)index.data(
                ConsoleItem::TypeRole).toInt();
    QColor backgroundColor;
    switch (itemType) {
    case ConsoleItem::DebugType:
        backgroundColor = selected ? QColor(CONSOLE_LOG_BACKGROUND_SELECTED_COLOR) :
                                     QColor(CONSOLE_LOG_BACKGROUND_COLOR);
        break;
    case ConsoleItem::WarningType:
        backgroundColor = selected ? QColor(CONSOLE_WARNING_BACKGROUND_SELECTED_COLOR) :
                                     QColor(CONSOLE_WARNING_BACKGROUND_COLOR);
        break;
    case ConsoleItem::ErrorType:
        backgroundColor = selected ? QColor(CONSOLE_ERROR_BACKGROUND_SELECTED_COLOR) :
                                     QColor(CONSOLE_ERROR_BACKGROUND_COLOR);
        break;
    case ConsoleItem::InputType:
    default:
        backgroundColor = selected ? QColor(CONSOLE_EDITOR_BACKGROUND_SELECTED_COLOR) :
                                     QColor(CONSOLE_EDITOR_BACKGROUND_COLOR);
        break;
    }
    if (!(index.flags() & Qt::ItemIsEditable))
        painter->setBrush(backgroundColor);
    painter->setPen(Qt::NoPen);
    painter->drawRect(rect);

    // Separator lines
    painter->setPen(QColor(CONSOLE_BORDER_COLOR));
    if (!(index.flags() & Qt::ItemIsEditable))
        painter->drawLine(0, rect.bottom(), rect.right(),
                          rect.bottom());
    painter->restore();
    return backgroundColor;
}
コード例 #17
0
ファイル: bookmarks.cpp プロジェクト: porphyr/arora
void BookmarksDialog::customContextMenuRequested(const QPoint &pos)
{
    QMenu menu;
    QModelIndex index = tree->indexAt(pos);
    index = index.sibling(index.row(), 0);
    QModelIndex sourceIndex = m_proxyModel->mapToSource(index);
    const BookmarkNode *node = m_bookmarksModel->node(sourceIndex);
    if (index.isValid() && node->type() != BookmarkNode::Folder) {
        menu.addAction(tr("Open"), this, SLOT(openInCurrentTab()));
        menu.addAction(tr("Open in New Tab"), this, SLOT(openInNewTab()));
        menu.addSeparator();
    }
    menu.addSeparator();
    QAction *renameAction = menu.addAction(tr("Edit Name"), this, SLOT(editName()));
    renameAction->setEnabled(index.flags() & Qt::ItemIsEditable);
    if (index.isValid() && node->type() != BookmarkNode::Folder) {
        menu.addAction(tr("Edit Address"), this, SLOT(editAddress()));
    }
    menu.addSeparator();
    QAction *deleteAction = menu.addAction(tr("Delete"), tree, SLOT(removeSelected()));
    deleteAction->setEnabled(index.flags() & Qt::ItemIsDragEnabled);
    menu.exec(QCursor::pos());
}
コード例 #18
0
QColor ConsoleItemDelegate::drawBackground(QPainter *painter, const QRect &rect,
                                              const QModelIndex &index,
                                              bool selected) const
{
    const Utils::Theme *theme = Utils::creatorTheme();
    painter->save();
    QColor backgroundColor = theme->color(selected
                                          ? Utils::Theme::BackgroundColorSelected
                                          : Utils::Theme::BackgroundColorNormal);
    if (!(index.flags() & Qt::ItemIsEditable))
        painter->setBrush(backgroundColor);
    painter->setPen(Qt::NoPen);
    painter->drawRect(rect);
    painter->restore();
    return backgroundColor;
}
コード例 #19
0
bool PrivateChatDialogModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!m_isEditable)
        return false;

    if (role == Qt::CheckStateRole && (index.flags() & Qt::ItemIsUserCheckable))
    {
        Player * player = PlayersList::instance()->getPlayer(index);
        if (!m_set.remove(player))
            m_set.insert(player);
        emit dataChanged(index, index);
        return true;
    }

    return QAbstractProxyModel::setData(index, value, role);
}
コード例 #20
0
Qt::ItemFlags CheckableProxyModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;

    QModelIndex sourceIndex = mapToSource(index);
    Qt::ItemFlags flags = sourceIndex.flags();
    if (index.column() == 0) {
        flags |= Qt::ItemIsUserCheckable;
        if (sourceIndex.model()->hasChildren(sourceIndex)) {
            flags |= Qt::ItemIsTristate;
        }
    }

    return flags;
}
コード例 #21
0
void PreferencesDialog::on_waveView_doubleClicked(const QModelIndex &index)
{
    if (index.column() == 1) {
        QColorDialog a;

        if (!(index.flags() & Qt::ItemIsEnabled)) return;
        quint32 color = index.data(Qt::UserRole).toUInt();

        a.setCurrentColor(QColor((QRgb)color));

        if (a.exec() == QColorDialog::Accepted) {
            quint32 cv = a.currentColor().rgba();

            waveFilterModel->setData(index, cv, Qt::UserRole);
            waveFilterModel->setData(index, a.currentColor(), Qt::BackgroundRole);

        }

    }
}
コード例 #22
0
ファイル: treeView.cpp プロジェクト: tavu/karakaxa
void views::treeView::play(const QModelIndex &index)
{
    //return if item is disabled
    if( !(index.flags() & Qt::ItemIsEnabled) || index.data(DISABLE_ROLE).toBool() )
    {
        return ;
    }

    core::nplList list;
    int row=index.row();
    for (int i=0;i<model()->rowCount(index.parent() );i++)
    {
        QModelIndex in=model()->index(i,0,index.parent() );
        if(in.isValid() )
        {
            QUrl u=in.data(URL_ROLE).toUrl();
            core::nplPointer t=core::nplTrack::getNplTrack(u);
            if(!t.isNull() && t->isValid() )
            {
                list<<t;
            }
            else if(in.row()<index.row() )
            {
                row--;
            }
        }
    }
	if(list.isEmpty() )
	{
		return ;
	}
    core::npList()->clear();
    core::npList()->insert(0,list);

    if(list.size() != model()->rowCount(index.parent() ) )
    {
        Basic::msg()->error(tr("Some media could not be inserted to playlist") );
    }
    
    core::engine()->play(row );
}
コード例 #23
0
ファイル: recentdlg.cpp プロジェクト: sergeyvl/vlasovsoft
    void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
    {
        QStyleOptionViewItem newOption;
        newOption = option;
        newOption.state &= ~QStyle::State_HasFocus;
        newOption.palette.setColor( QPalette::Disabled, QPalette::Text, Qt::black );

        QTableWidget* pWidget = static_cast<QTableWidget*>( parent() );
        RecentTableWidgetItem* pItem = static_cast<RecentTableWidgetItem*>(pWidget->item(index.row(), index.column()));

        painter->setFont(fontTitle);
        QFontMetrics tfm(fontTitle);
        int fontTitleSize = tfm.height();
        QRect titleRect( newOption.rect.x(), newOption.rect.y(), newOption.rect.width(), fontTitleSize );
        painter->drawText( titleRect, Qt::TextSingleLine, tfm.elidedText(pItem->title, Qt::ElideRight, newOption.rect.width() ));

        painter->setFont(fontInfo);
        QFontMetrics ifm(fontInfo);
        int fontAuthorSize = ifm.height();
        QRect infoRect( newOption.rect.x(), newOption.rect.y() + fontTitleSize, newOption.rect.width(), fontAuthorSize );

        int percentWidth = ifm.boundingRect(pItem->percent).width();
        infoRect.adjust(0,0,-percentWidth,0);

        painter->drawText( infoRect, Qt::TextSingleLine, ifm.elidedText(pItem->info, Qt::ElideRight, infoRect.width() ) );

        QRect percentRect( infoRect.right(), infoRect.top(), percentWidth, infoRect.height() );
        painter->drawText( percentRect, Qt::TextSingleLine, pItem->percent );

        if (index.flags() & Qt::ItemIsSelectable)
        {
            Qt::GlobalColor lineColor = Qt::black;
            int lineWidth = newOption.state & QStyle::State_Selected ? 5:0;
            QPen pen(lineColor, lineWidth, Qt::SolidLine);
            painter->setPen(pen);
            painter->drawLine(newOption.rect.left(), newOption.rect.bottom()-lineWidth/2, newOption.rect.right(), newOption.rect.bottom()-lineWidth/2);
        }
    }
コード例 #24
0
void RatingComboBoxDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
                                   const QModelIndex& index) const
{
    QVariant value  = index.data(Qt::DisplayRole);
    bool selectable = index.flags() & Qt::ItemIsSelectable;

    if (value.type() == QVariant::Int)
    {
        painter->save();
        drawBackground(painter, option, index);
        drawDisplay(painter, option, option.rect, QString());

        // our custom painting
        drawRating(painter, option.rect, value.toInt(), selectable);

        drawFocus(painter, option, option.rect);
        painter->restore();
    }
    else
    {
        return QItemDelegate::paint(painter, option, index);
    }
}
コード例 #25
0
QString QmitkStatisticsModelToStringConverter::Iterate(const QModelIndex &index,
                                                       const QAbstractItemModel *model,
                                                       int depth) const
{
  QString content;
  if (index.isValid())
  {
    content = index.data().toString();
  }
  if (!model->hasChildren(index) || (index.flags() & Qt::ItemNeverHasChildren))
  {
    return content;
  }
  else
  {
    content += m_lineDelimiter;
  }

  auto rows = model->rowCount(index);
  auto cols = model->columnCount(index);
  for (int i = 0; i < rows; ++i)
  {
    if (i > 0)
    {
      content += m_lineDelimiter;
    }
    for (int j = 0; j < cols; ++j)
    {
      if (j > 0)
      {
        content += m_columnDelimiterWithSpace;
      }
      content += Iterate(model->index(i, j, index), model, depth + 1);
    }
  }
  return content;
}
コード例 #26
0
void QCompleterPrivate::_q_complete(QModelIndex index, bool highlighted)
{
    Q_Q(QCompleter);
    QString completion;

    if (!index.isValid() || (!proxy->showAll && (index.row() >= proxy->engine->matchCount()))) {
        completion = prefix;
    } else {
        if (!(index.flags() & Qt::ItemIsEnabled))
            return;
        QModelIndex si = proxy->mapToSource(index);
        si = si.sibling(si.row(), column); // for clicked()
        completion = q->pathFromIndex(si);
#ifndef QT_NO_DIRMODEL
        // add a trailing separator in inline
        if (mode == QCompleter::InlineCompletion) {
            if (qobject_cast<QDirModel *>(proxy->sourceModel()) && QFileInfo(completion).isDir())
                completion += QDir::separator();
        }
#endif
#ifndef QT_NO_FILESYSTEMMODEL
        // add a trailing separator in inline
        if (mode == QCompleter::InlineCompletion) {
            if (qobject_cast<QFileSystemModel *>(proxy->sourceModel()) && QFileInfo(completion).isDir())
                completion += QDir::separator();
        }
#endif
    }

    if (highlighted) {
        emit q->highlighted(index);
        emit q->highlighted(completion);
    } else {
        emit q->activated(index);
        emit q->activated(completion);
    }
}
コード例 #27
0
ファイル: ModelUtils.cpp プロジェクト: ElwooD07/BdContainer
bool model::utils::IsItemEditable(const QModelIndex& index)
{
	return (index.isValid() && (index.flags() & Qt::ItemIsEditable) == Qt::ItemIsEditable);
}
コード例 #28
0
QItemSelectionModel::SelectionFlags AMActionHistoryTreeView3::selectionCommand(const QModelIndex &index, const QEvent *selectionEvent) const{
	// Initialize by calling the parent version
	QItemSelectionModel::SelectionFlags retFlags = QTreeView::selectionCommand(index, selectionEvent);
	bool hasShiftModifier, hasControlModifier;

	// If we have a valid index we have a lot of work to do (also make sure this thing is actually an AMActionHistoryModel viewing tree)
	if(index.isValid()){
		AMActionHistoryModel3 *historyModel = qobject_cast<AMActionHistoryModel3*>(model());


		// We only care about the mouse button press events otherwise return the parent class call
		if( !historyModel || (selectionEvent->type() != QEvent::MouseButtonPress) )
			return QTreeView::selectionCommand(index, selectionEvent);
		QMouseEvent *mouseEvent = (QMouseEvent*)selectionEvent;

		// Ignore clicks on non-selectable indices
		// We can ignore: not enabled indexes, and not selectable indexes
		if(!index.flags().testFlag(Qt::ItemIsEnabled) || !index.flags().testFlag(Qt::ItemIsSelectable))
			return QTreeView::selectionCommand(index, selectionEvent);

		// Grab keyboard shift and control modifiers
		Qt::KeyboardModifiers currentModifiers = mouseEvent->modifiers();
		hasControlModifier = currentModifiers&Qt::ControlModifier;
		hasShiftModifier = currentModifiers&Qt::ShiftModifier;

		ParentSelectMap selectMap = model()->data(index, AMActionHistoryModel3::ParentSelectRole).value<ParentSelectMap>();
		// This is pretty bad, you can tell too much is in here that doesn't belong when I need to do a const cast
		AMActionHistoryTreeView3 *checkViewer = const_cast<AMActionHistoryTreeView3*>(this);
		bool parentIsSelected = false;
		// Figure out if the parent is selected via the mapping or the selection model
		if(index.parent().isValid()){
			ParentSelectMap parentsSelectMap = model()->data(index.parent(), AMActionHistoryModel3::ParentSelectRole).value<ParentSelectMap>();
			if(parentsSelectMap.contains(checkViewer))
				parentIsSelected |= parentsSelectMap.value(checkViewer);
			parentIsSelected |= selectionModel()->isSelected(index.parent());
		}

		// On control clicks where the parent is selected and this index is as well, do the group deselect and return noUpdate in the selection flags
		if(hasControlModifier && index.parent().isValid() && parentIsSelected && selectMap.contains(checkViewer) && selectMap.value(checkViewer)){
			historyModel->markIndexGroupAsDeselected(index, checkViewer);
			return QItemSelectionModel::NoUpdate;
		}
		// On control clicks where the parent is selected and this index is not, do the group select and return noUpdate in the selection flags
		else if(hasControlModifier && index.parent().isValid() && parentIsSelected && selectMap.contains(checkViewer) && !selectMap.value(checkViewer)){
			historyModel->markIndexGroupAsSelected(index, checkViewer);
			return QItemSelectionModel::NoUpdate;
		}

		// Ignore regular clicks on the an index that is already actually selected if it's the only one selected
		if( !hasControlModifier && (actuallySelectedByClickingCount_ == 1) && (selectionModel()->selectedIndexes().contains(index)) ){
			return QItemSelectionModel::NoUpdate;
		}
	}

	// Log some flags ... might be an easier way now that I know how to use QFlag::testFlag()
	bool clearFlag = (retFlags&QItemSelectionModel::Clear);
	bool selectFlag = (retFlags&QItemSelectionModel::Select);
	bool deselectFlag = (retFlags&QItemSelectionModel::Deselect);
	bool toggleFlag = (retFlags&QItemSelectionModel::Toggle);
	bool indexAlreadyOn = selectionModel()->selectedIndexes().contains(index);
	bool noUpdateFlag = (retFlags&QItemSelectionModel::NoUpdate);

	// An actual selection! Selected OR (Toggled AND NOT Currently On) OR (noUpdate AND Currently On)
	bool selectedTrue = selectFlag || (toggleFlag && !indexAlreadyOn) || (noUpdateFlag && indexAlreadyOn);
	// An actual deselection! Deselected OR (Toggled AND Currently On) OR (noUpdate AND NOT Currently On) OR (Actually selected an invalid index)
	bool selectedFalse = deselectFlag || (toggleFlag && indexAlreadyOn) || (noUpdateFlag && !indexAlreadyOn) || (selectedTrue && !index.isValid());

	// If we actually selected and the column is 0 (we only care about that one) log the state and emit actuallySelectedByClicking
	if(selectedTrue && (index.column() == 0) ){
		lastClickWasDeselect_ = false;
		lastClickedIndex_ = index;
		emit actuallySelectedByClicking(index, clearFlag);
	}
	// If we actually deselected and the column is 0 (we only care about that one) log the state (particularily lastClickWasDeselect) and emit actuallyDeselectedByClicking
	else if(selectedFalse && (index.column() == 0) ){
		QModelIndexList currentSelections = selectionModel()->selection().indexes();
		if(currentSelections.count() == 2){
			currentSelections.removeOne(index);
			lastClickedIndex_ = currentSelections.at(0);
			lastClickWasDeselect_ = false;
		}
		else
			lastClickWasDeselect_ = true;
		emit actuallyDeselectedByClicking(index, clearFlag);
	}
	// If neither selected nor deselected but clear flag is on then emit clearedByClicking
	else if(clearFlag){
		lastClickWasDeselect_ = false;
		emit clearedByClicking();
	}

	// Return the flags we have
	return retFlags;
}
コード例 #29
0
void AMActionHistoryTreeView3::mousePressEvent(QMouseEvent *event){
	// Ignore mouse clicks if the cursor shows forbidden
	if(shiftKeyDown_ && hasOverriddenShiftCursor_){
		event->ignore();
	}
	// Actually handling valid shift-clicks
	else if(shiftKeyDown_){
		AMActionHistoryModel3 *historyModel = qobject_cast<AMActionHistoryModel3*>(model());
		QModelIndex index = indexAt(event->pos());

		// We can ignore: bad models, invalid indexes, not enabled indexes, and not selectable indexes
		if(!historyModel || !index.isValid() || !index.flags().testFlag(Qt::ItemIsEnabled) || !index.flags().testFlag(Qt::ItemIsSelectable))
			event->ignore();

		// Grab current selection from model and the indices between the shift click
		QItemSelection currentSelection = selectionModel()->selection();
		QItemSelection newSelection = historyModel->indicesBetween(index, lastClickedIndex_);

		// Call the selectionCommand function and merge the current and new selections
		QItemSelectionModel::SelectionFlags command = selectionCommand(index, event);
		currentSelection.merge(newSelection, command);

		// Clear the selection and select the combined list
		selectionModel()->clearSelection();
		selectionModel()->select(currentSelection, command);

		// Grab the list indices between the shift click so we can apply the right parentSelected states to them
		QModelIndexList interiorIndices = newSelection.indexes();
		// We only care about lists that have interior elements, the indicesBetween call returns the ends as well
		if(interiorIndices.count() >= 2){
			// Grab the clear flag for the signal emitted below
			bool clearFlag = command.testFlag(QItemSelectionModel::Clear);

			// Not sure if the indices are ordered correctly, so figure out the min and max to remove them (they should be the ends we don't care about)
			QModelIndex minRowIndex = interiorIndices.at(0);
			int minRowValue = minRowIndex.row();
			QModelIndex maxRowIndex = interiorIndices.at(1);
			int maxRowValue = maxRowIndex.row();
			for(int x = 0; x < interiorIndices.count(); x++){
				if(interiorIndices.at(x).row() < minRowValue){
					minRowIndex = interiorIndices.at(x);
					minRowValue = minRowIndex.row();
				}
				if(interiorIndices.at(x).row() > maxRowValue){
					maxRowIndex = interiorIndices.at(x);
					maxRowValue = maxRowIndex.row();
				}
			}

			// Remove both ends
			interiorIndices.removeOne(maxRowIndex);
			interiorIndices.removeOne(minRowIndex);

			// For all interior indices emulate a click by emitting the actuallySelectedByClicking signal ... then the regular chain of events can happen to parentSelect the children
			for(int x = 0; x < interiorIndices.count(); x++)
				emit actuallySelectedByClicking(interiorIndices.at(x), clearFlag);
		}

		// Accept the event
		event->accept();
	}
	// Ignore mouse clicks if the cursor shows forbidden
	else if(controlKeyDown_ && hasOverriddenControlCursor_){
		event->ignore();
	}
	// Falls through, call the parent class
	else
		QTreeView::mousePressEvent(event);
}
コード例 #30
0
bool KoDocumentSectionDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if ((event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonDblClick)
        && (index.flags() & Qt::ItemIsEnabled))
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);

        const QRect iconsRect_ = iconsRect(option, index).translated(option.rect.topLeft());

        if (iconsRect_.isValid() && iconsRect_.contains(mouseEvent->pos())) {
            const int iconWidth = option.decorationSize.width();
            int xPos = mouseEvent->pos().x() - iconsRect_.left();
            if (xPos % (iconWidth + d->margin) < iconWidth) { //it's on an icon, not a margin
                Model::PropertyList propertyList = index.data(Model::PropertiesRole).value<Model::PropertyList>();
                int clickedProperty = -1;
                // Discover which of all properties was clicked
                for (int i = 0; i < propertyList.count(); ++i) {
                    if (propertyList[i].isMutable) {
                        xPos -= iconWidth + d->margin;
                    }
                    ++clickedProperty;
                    if (xPos < 0) break;
                }
                // Using Ctrl+click to enter stasis
                if (mouseEvent->modifiers() == Qt::ControlModifier
                    && propertyList[clickedProperty].canHaveStasis) {
                    // STEP 0: Prepare to Enter or Leave control key stasis
                    quint16 numberOfLeaves = model->rowCount(index.parent());
                    QModelIndex eachItem;
                    // STEP 1: Go.
                    if (propertyList[clickedProperty].isInStasis == false) { // Enter
                        /* Make every leaf of this node go State = False, saving the old property value to stateInStasis */
                        for (quint16 i = 0; i < numberOfLeaves; ++i) { // Foreach leaf in the node (index.parent())
                            eachItem = model->index(i, 0, index.parent());
                            // The entire property list has to be altered because model->setData cannot set individual properties
                            Model::PropertyList eachPropertyList = eachItem.data(Model::PropertiesRole).value<Model::PropertyList>();
                            eachPropertyList[clickedProperty].stateInStasis = eachPropertyList[clickedProperty].state.toBool();
                            eachPropertyList[clickedProperty].state = false;
                            eachPropertyList[clickedProperty].isInStasis = true;
                            model->setData(eachItem, QVariant::fromValue(eachPropertyList), Model::PropertiesRole);
                        }
                        /* Now set the current node's clickedProperty back to True, to save the user time
                        (obviously, if the user is clicking one item with ctrl+click, he's interested in that
                        item to have a True property value while the others are in stasis and set to False) */
                        // First refresh propertyList, otherwise old data will be saved back causing bugs
                        propertyList = index.data(Model::PropertiesRole).value<Model::PropertyList>();
                        propertyList[clickedProperty].state = true;
                        model->setData(index, QVariant::fromValue(propertyList), Model::PropertiesRole);
                    } else { // Leave
                        /* Make every leaf of this node go State = stateInStasis */
                        for (quint16 i = 0; i < numberOfLeaves; ++i) {
                            eachItem = model->index(i, 0, index.parent());
                            // The entire property list has to be altered because model->setData cannot set individual properties
                            Model::PropertyList eachPropertyList = eachItem.data(Model::PropertiesRole).value<Model::PropertyList>();
                            eachPropertyList[clickedProperty].state = eachPropertyList[clickedProperty].stateInStasis;
                            eachPropertyList[clickedProperty].isInStasis = false;
                            model->setData(eachItem, QVariant::fromValue(eachPropertyList), Model::PropertiesRole);
                        }
                    }
                } else {
                    propertyList[clickedProperty].state = !propertyList[clickedProperty].state.toBool();
                    model->setData(index, QVariant::fromValue(propertyList), Model::PropertiesRole);
                }
            }
            return true;
        }
        if (mouseEvent->button() != Qt::LeftButton) {
            d->view->setCurrentIndex(index);
            return false;
        }
    }
    else if (event->type() == QEvent::ToolTip) {
        QHelpEvent *helpEvent = static_cast<QHelpEvent*>(event);
        d->tip.showTip(d->view, helpEvent->pos(), option, index);
        return true;
    } else if (event->type() == QEvent::Leave) {
        d->tip.hide();
    }

    return false;
}