void QgsWFSSourceSelect::buildQuery( const QModelIndex &index ) { if ( !index.isValid() ) { return; } const QString typeName = index.sibling( index.row(), MODEL_IDX_NAME ).data().toString(); //get available fields for wfs layer QgsWfsConnection connection( cmbConnections->currentText() ); QgsWFSDataSourceURI uri( connection.uri().uri() ); uri.setTypeName( typeName ); QgsDataProvider::ProviderOptions providerOptions; QgsWFSProvider p( uri.uri(), providerOptions, mCaps ); if ( !p.isValid() ) { QMessageBox *box = new QMessageBox( QMessageBox::Critical, tr( "Server exception" ), tr( "DescribeFeatureType failed" ), QMessageBox::Ok, this ); box->setAttribute( Qt::WA_DeleteOnClose ); box->setModal( true ); box->setObjectName( QStringLiteral( "WFSFeatureTypeErrorBox" ) ); if ( !property( "hideDialogs" ).toBool() ) box->open(); return; } QModelIndex filterIndex = index.sibling( index.row(), MODEL_IDX_SQL ); QString sql( filterIndex.data().toString() ); QString displayedTypeName( typeName ); if ( !mCaps.setAmbiguousUnprefixedTypename.contains( QgsWFSUtils::removeNamespacePrefix( typeName ) ) ) displayedTypeName = QgsWFSUtils::removeNamespacePrefix( typeName ); QString allSql( "SELECT * FROM " + QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) ); if ( sql.isEmpty() ) { sql = allSql; } QgsSQLComposerDialog *d = new QgsSQLComposerDialog( this ); QgsWFSValidatorCallback *validatorCbk = new QgsWFSValidatorCallback( d, uri, allSql, mCaps ); d->setSQLValidatorCallback( validatorCbk ); QgsWFSTableSelectedCallback *tableSelectedCbk = new QgsWFSTableSelectedCallback( d, uri, mCaps ); d->setTableSelectedCallback( tableSelectedCbk ); const bool bSupportJoins = mCaps.featureTypes.size() > 1 && mCaps.supportsJoins; d->setSupportMultipleTables( bSupportJoins, QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) ); QMap< QString, QString > mapTypenameToTitle; Q_FOREACH ( const QgsWfsCapabilities::FeatureType f, mCaps.featureTypes ) mapTypenameToTitle[f.name] = f.title; QList< QgsSQLComposerDialog::PairNameTitle > tablenames; tablenames << QgsSQLComposerDialog::PairNameTitle( QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ), mapTypenameToTitle[typeName] ); if ( bSupportJoins ) { for ( int i = 0; i < mModel->rowCount(); i++ ) { const QString iterTypename = mModel->index( i, MODEL_IDX_NAME ).data().toString(); if ( iterTypename != typeName ) { QString displayedIterTypename( iterTypename ); QString unprefixedIterTypename( QgsWFSUtils::removeNamespacePrefix( iterTypename ) ); if ( !mCaps.setAmbiguousUnprefixedTypename.contains( unprefixedIterTypename ) ) displayedIterTypename = unprefixedIterTypename; tablenames << QgsSQLComposerDialog::PairNameTitle( QgsSQLStatement::quotedIdentifierIfNeeded( displayedIterTypename ), mapTypenameToTitle[iterTypename] ); } } } d->addTableNames( tablenames ); QList< QgsSQLComposerDialog::Function> functionList; Q_FOREACH ( const QgsWfsCapabilities::Function &f, mCaps.functionList ) { QgsSQLComposerDialog::Function dialogF; dialogF.name = f.name; dialogF.returnType = f.returnType; dialogF.minArgs = f.minArgs; dialogF.maxArgs = f.maxArgs; Q_FOREACH ( const QgsWfsCapabilities::Argument &arg, f.argumentList ) { dialogF.argumentList << QgsSQLComposerDialog::Argument( arg.name, arg.type ); } functionList << dialogF; } d->addFunctions( functionList ); QList< QgsSQLComposerDialog::Function> spatialPredicateList; Q_FOREACH ( const QgsWfsCapabilities::Function &f, mCaps.spatialPredicatesList ) { QgsSQLComposerDialog::Function dialogF; dialogF.name = f.name; dialogF.returnType = f.returnType; dialogF.minArgs = f.minArgs; dialogF.maxArgs = f.maxArgs; Q_FOREACH ( const QgsWfsCapabilities::Argument &arg, f.argumentList ) { dialogF.argumentList << QgsSQLComposerDialog::Argument( arg.name, arg.type ); } spatialPredicateList << dialogF; } d->addSpatialPredicates( spatialPredicateList ); QList< QgsSQLComposerDialog::PairNameType> fieldList; QString fieldNamePrefix; if ( bSupportJoins ) { fieldNamePrefix = QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) + "."; } Q_FOREACH ( const QgsField &field, p.fields().toList() ) { QString fieldName( fieldNamePrefix + QgsSQLStatement::quotedIdentifierIfNeeded( field.name() ) ); fieldList << QgsSQLComposerDialog::PairNameType( fieldName, field.typeName() ); } if ( !p.geometryAttribute().isEmpty() ) { QString fieldName( fieldNamePrefix + QgsSQLStatement::quotedIdentifierIfNeeded( p.geometryAttribute() ) ); fieldList << QgsSQLComposerDialog::PairNameType( fieldName, QStringLiteral( "geometry" ) ); } fieldList << QgsSQLComposerDialog::PairNameType( fieldNamePrefix + "*", QString() ); d->addColumnNames( fieldList, QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) ); d->setSql( sql ); mSQLIndex = index; mSQLComposerDialog = d; // For testability, do not use exec() if ( property( "hideDialogs" ).toBool() ) { d->setAttribute( Qt::WA_DeleteOnClose ); d->setModal( true ); d->open(); connect( d, &QDialog::accepted, this, &QgsWFSSourceSelect::updateSql ); } else { // But we need to use exec() for real GUI, otherwise it does not look // right on Mac if ( d->exec() ) { updateSql(); } delete d; } }
void PropertyEditorDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { editor->setProperty("displayString", index.data(Qt::DisplayRole)); QStyledItemDelegate::setEditorData(editor, index); }
void QmlConsoleItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QmlConsoleEdit *edtr = qobject_cast<QmlConsoleEdit *>(editor); edtr->insertPlainText(index.data(ConsoleItem::ExpressionRole).toString()); }
void CIPEditDelegate::setEditorData(QWidget * editor, const QModelIndex & index) const { QString value = index.data().toString(); QLineEdit * lineEdit = static_cast<QLineEdit *>(editor); lineEdit->setText(value); }
void PlaylistDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { QStyleOptionViewItemV4 opt = option; initStyleOption( &opt, QModelIndex() ); qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter ); if ( option.state & QStyle::State_Selected && option.state & QStyle::State_Active ) { opt.palette.setColor( QPalette::Text, opt.palette.color( QPalette::HighlightedText ) ); } painter->save(); painter->setRenderHint( QPainter::Antialiasing ); painter->setPen( opt.palette.color( QPalette::Text ) ); QTextOption to; to.setAlignment( Qt::AlignCenter ); QFont font = opt.font; font.setPixelSize( 10 ); QFont boldFont = font; boldFont.setBold( true ); boldFont.setPixelSize( 11 ); QFont figFont = boldFont; figFont.setPixelSize( 10 ); QPixmap icon; RecentlyPlayedPlaylistsModel::PlaylistTypes type = (RecentlyPlayedPlaylistsModel::PlaylistTypes)index.data( RecentlyPlayedPlaylistsModel::PlaylistTypeRole ).toInt(); if( type == RecentlyPlayedPlaylistsModel::StaticPlaylist ) icon = m_playlistIcon; else if( type == RecentlyPlayedPlaylistsModel::AutoPlaylist ) icon = m_autoIcon; else if( type == RecentlyPlayedPlaylistsModel::Station ) icon = m_stationIcon; QRect pixmapRect = option.rect.adjusted( 10, 13, -option.rect.width() + 48, -13 ); icon = icon.scaled( pixmapRect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation ); painter->drawPixmap( pixmapRect, icon ); if ( type != RecentlyPlayedPlaylistsModel::Station ) { painter->save(); painter->setFont( figFont ); QString tracks = index.data( RecentlyPlayedPlaylistsModel::TrackCountRole ).toString(); int width = painter->fontMetrics().width( tracks ); // int bottomEdge = pixmapRect // right edge 10px past right edge of pixmapRect // bottom edge flush with bottom of pixmap QRect rect( pixmapRect.right() - width , 0, width - 8, 0 ); rect.adjust( -1, 0, 0, 0 ); rect.setTop( pixmapRect.bottom() - painter->fontMetrics().height() - 1 ); rect.setBottom( pixmapRect.bottom() + 1 ); QColor figColor( "#464b55" ); painter->setPen( figColor ); painter->setBrush( figColor ); TomahawkUtils::drawBackgroundAndNumbers( painter, tracks, rect ); painter->restore(); } QPixmap avatar = index.data( RecentlyPlayedPlaylistsModel::PlaylistRole ).value< Tomahawk::playlist_ptr >()->author()->avatar( Source::FancyStyle ); if ( avatar.isNull() ) avatar = m_defaultAvatar; QRect r( option.rect.width() - avatar.width() - 10, option.rect.top() + option.rect.height()/2 - avatar.height()/2, avatar.width(), avatar.height() ); painter->drawPixmap( r, avatar ); painter->setFont( font ); QString author = index.data( RecentlyPlayedPlaylistsModel::PlaylistRole ).value< Tomahawk::playlist_ptr >()->author()->friendlyName(); if ( author.indexOf( '@' ) > 0 ) author = author.mid( 0, author.indexOf( '@' ) ); const int w = painter->fontMetrics().width( author ) + 2; QRect avatarNameRect( opt.rect.width() - 10 - w, r.bottom(), w, opt.rect.bottom() - r.bottom() ); painter->drawText( avatarNameRect, author, QTextOption( Qt::AlignCenter ) ); const int leftEdge = opt.rect.width() - qMin( avatarNameRect.left(), r.left() ); QString descText; if ( type == RecentlyPlayedPlaylistsModel::Station ) { descText = index.data( RecentlyPlayedPlaylistsModel::DynamicPlaylistRole ).value< Tomahawk::dynplaylist_ptr >()->generator()->sentenceSummary(); } else { descText = index.data( RecentlyPlayedPlaylistsModel::ArtistRole ).toString(); } QColor c = painter->pen().color(); if ( !( option.state & QStyle::State_Selected && option.state & QStyle::State_Active ) ) { painter->setPen( QColor( Qt::gray ).darker() ); } QRect rectText = option.rect.adjusted( 66, 20, -leftEdge - 10, -8 ); #ifdef Q_WS_MAC rectText.adjust( 0, 1, 0, 0 ); #elif defined Q_WS_WIN rectText.adjust( 0, 2, 0, 0 ); #endif painter->drawText( rectText, descText ); painter->setPen( c ); painter->setFont( font ); painter->setFont( boldFont ); painter->drawText( option.rect.adjusted( 56, 6, -100, -option.rect.height() + 20 ), index.data().toString() ); painter->restore(); }
bool ModListSortProxy::lessThan(const QModelIndex &left, const QModelIndex &right) const { if (sourceModel()->hasChildren(left) || sourceModel()->hasChildren(right)) { return QSortFilterProxyModel::lessThan(left, right); } bool lOk, rOk; int leftIndex = left.data(Qt::UserRole + 1).toInt(&lOk); int rightIndex = right.data(Qt::UserRole + 1).toInt(&rOk); if (!lOk || !rOk) { return false; } ModInfo::Ptr leftMod = ModInfo::getByIndex(leftIndex); ModInfo::Ptr rightMod = ModInfo::getByIndex(rightIndex); bool lt = false; { QModelIndex leftPrioIdx = left.sibling(left.row(), ModList::COL_PRIORITY); QVariant leftPrio = leftPrioIdx.data(); if (!leftPrio.isValid()) leftPrio = left.data(Qt::UserRole); QModelIndex rightPrioIdx = right.sibling(right.row(), ModList::COL_PRIORITY); QVariant rightPrio = rightPrioIdx.data(); if (!rightPrio.isValid()) rightPrio = right.data(Qt::UserRole); lt = leftPrio.toInt() < rightPrio.toInt(); } switch (left.column()) { case ModList::COL_FLAGS: { std::vector<ModInfo::EFlag> leftFlags = leftMod->getFlags(); std::vector<ModInfo::EFlag> rightFlags = rightMod->getFlags(); if (leftFlags.size() != rightFlags.size()) { lt = leftFlags.size() < rightFlags.size(); } else { lt = flagsId(leftFlags) < flagsId(rightFlags); } } break; case ModList::COL_CONTENT: { std::vector<ModInfo::EContent> lContent = leftMod->getContents(); std::vector<ModInfo::EContent> rContent = rightMod->getContents(); if (lContent.size() != rContent.size()) { lt = lContent.size() < rContent.size(); } int lValue = 0; int rValue = 0; for (ModInfo::EContent content : lContent) { lValue += 2 << (unsigned int)content; } for (ModInfo::EContent content : rContent) { rValue += 2 << (unsigned int)content; } lt = lValue < rValue; } break; case ModList::COL_NAME: { int comp = QString::compare(leftMod->name(), rightMod->name(), Qt::CaseInsensitive); if (comp != 0) lt = comp < 0; } break; case ModList::COL_CATEGORY: { if (leftMod->getPrimaryCategory() != rightMod->getPrimaryCategory()) { if (leftMod->getPrimaryCategory() < 0) lt = false; else if (rightMod->getPrimaryCategory() < 0) lt = true; else { try { CategoryFactory &categories = CategoryFactory::instance(); QString leftCatName = categories.getCategoryName(categories.getCategoryIndex(leftMod->getPrimaryCategory())); QString rightCatName = categories.getCategoryName(categories.getCategoryIndex(rightMod->getPrimaryCategory())); lt = leftCatName < rightCatName; } catch (const std::exception &e) { qCritical("failed to compare categories: %s", e.what()); } } } } break; case ModList::COL_MODID: { if (leftMod->getNexusID() != rightMod->getNexusID()) lt = leftMod->getNexusID() < rightMod->getNexusID(); } break; case ModList::COL_VERSION: { if (leftMod->getVersion() != rightMod->getVersion()) lt = leftMod->getVersion() < rightMod->getVersion(); } break; case ModList::COL_INSTALLTIME: { QDateTime leftTime = left.data().toDateTime(); QDateTime rightTime = right.data().toDateTime(); if (leftTime != rightTime) return leftTime < rightTime; } break; case ModList::COL_PRIORITY: { // nop, already compared by priority } break; } return lt; }
void GrepOutputDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { // there is no function in QString to left-trim. A call to remove this this regexp does the job static const QRegExp leftspaces("^\\s*", Qt::CaseSensitive, QRegExp::RegExp); // rich text component const GrepOutputModel *model = dynamic_cast<const GrepOutputModel *>(index.model()); const GrepOutputItem *item = dynamic_cast<const GrepOutputItem *>(model->itemFromIndex(index)); QStyleOptionViewItem options = option; initStyleOption(&options, index); // building item representation QTextDocument doc; QTextCursor cur(&doc); QPalette::ColorGroup cg = options.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; QPalette::ColorRole cr = options.state & QStyle::State_Selected ? QPalette::HighlightedText : QPalette::Text; QTextCharFormat fmt = cur.charFormat(); fmt.setFont(options.font); if(item && item->isText()) { // Use custom manual highlighting const KTextEditor::Range rng = item->change()->m_range; // the line number appears grayed fmt.setForeground(options.palette.brush(QPalette::Disabled, cr)); cur.insertText(i18n("Line %1: ",item->lineNumber()), fmt); // switch to normal color fmt.setForeground(options.palette.brush(cg, cr)); cur.insertText(item->text().left(rng.start().column()).remove(leftspaces), fmt); fmt.setFontWeight(QFont::Bold); if ( !(options.state & QStyle::State_Selected) ) { QColor bgHighlight = option.palette.color(QPalette::AlternateBase); fmt.setBackground(bgHighlight); } cur.insertText(item->text().mid(rng.start().column(), rng.end().column() - rng.start().column()), fmt); fmt.clearBackground(); fmt.setFontWeight(QFont::Normal); cur.insertText(item->text().right(item->text().length() - rng.end().column()), fmt); }else{ QString text; if(item) text = item->text(); else text = index.data().toString(); // Simply insert the text as html. We use this for the titles. doc.setHtml(text); } painter->save(); options.text = QString(); // text will be drawn separately options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter, options.widget); // set correct draw area QRect clip = options.widget->style()->subElementRect(QStyle::SE_ItemViewItemText, &options); QFontMetrics metrics(options.font); painter->translate(clip.topLeft() - QPoint(0, metrics.descent())); // We disable the clipping for now, as it leads to strange clipping errors // clip.setTopLeft(QPoint(0,0)); // painter->setClipRect(clip); QAbstractTextDocumentLayout::PaintContext ctx; // ctx.clip = clip; painter->setBackground(Qt::transparent); doc.documentLayout()->draw(painter, ctx); painter->restore(); }
void TreeItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { PlayableItem* item = m_model->sourceModel()->itemFromIndex( m_model->mapToSource( index ) ); if ( !item ) return; QTextOption textOption( Qt::AlignVCenter | (Qt::Alignment)index.data( Qt::TextAlignmentRole ).toUInt() ); textOption.setWrapMode( QTextOption::NoWrap ); QString text; if ( !item->artist().isNull() ) { text = item->artist()->name(); } else if ( !item->album().isNull() ) { text = item->album()->name(); } else if ( !item->result().isNull() || !item->query().isNull() ) { float opacity = item->result().isNull() ? 0.0 : item->result()->score(); opacity = qMax( (float)0.3, opacity ); QColor textColor = TomahawkUtils::alphaBlend( option.palette.color( QPalette::Foreground ), option.palette.color( QPalette::Background ), opacity ); { QStyleOptionViewItemV4 o = option; initStyleOption( &o, QModelIndex() ); painter->save(); o.palette.setColor( QPalette::Text, textColor ); if ( o.state & QStyle::State_Selected && o.state & QStyle::State_Active ) { o.palette.setColor( QPalette::Text, o.palette.color( QPalette::HighlightedText ) ); } if ( item->isPlaying() ) { textColor = TomahawkUtils::Colors::NOW_PLAYING_ITEM_TEXT; o.palette.setColor( QPalette::Highlight, TomahawkUtils::Colors::NOW_PLAYING_ITEM ); o.palette.setColor( QPalette::Text, TomahawkUtils::Colors::NOW_PLAYING_ITEM_TEXT ); o.state |= QStyle::State_Selected; } int oldX = 0; if ( m_view->header()->visualIndex( index.column() ) == 0 ) { oldX = o.rect.x(); o.rect.setX( 0 ); } qApp->style()->drawControl( QStyle::CE_ItemViewItem, &o, painter ); if ( oldX > 0 ) o.rect.setX( oldX ); if ( m_view->hoveredIndex() == index && !index.data().toString().isEmpty() && index.column() == 0 ) { o.rect.setWidth( o.rect.width() - o.rect.height() ); QRect arrowRect( o.rect.x() + o.rect.width(), o.rect.y() + 1, o.rect.height() - 2, o.rect.height() - 2 ); QPixmap infoIcon = TomahawkUtils::defaultPixmap( TomahawkUtils::InfoIcon, TomahawkUtils::Original, arrowRect.size() ); painter->drawPixmap( arrowRect, infoIcon ); } { QRect r = o.rect.adjusted( 3, 0, 0, 0 ); // Paint Now Playing Speaker Icon if ( item->isPlaying() && m_view->header()->visualIndex( index.column() ) == 0 ) { const int pixMargin = 1; const int pixHeight = r.height() - pixMargin * 2; QRect npr = r.adjusted( pixMargin, pixMargin, pixHeight - r.width() + pixMargin, -pixMargin ); painter->drawPixmap( npr, TomahawkUtils::defaultPixmap( TomahawkUtils::NowPlayingSpeaker, TomahawkUtils::Original, npr.size() ) ); r.adjust( pixHeight + 6, 0, 0, 0 ); } painter->setPen( o.palette.text().color() ); QString text = painter->fontMetrics().elidedText( index.data().toString(), Qt::ElideRight, r.width() - 3 ); painter->drawText( r.adjusted( 0, 1, 0, 0 ), text, textOption ); } painter->restore(); } return; } else return; if ( text.trimmed().isEmpty() ) text = tr( "Unknown" ); QStyleOptionViewItemV4 opt = option; initStyleOption( &opt, QModelIndex() ); qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter ); if ( option.state & QStyle::State_Selected ) { opt.palette.setColor( QPalette::Text, opt.palette.color( QPalette::HighlightedText ) ); } if ( index.column() > 0 ) return; painter->save(); painter->setRenderHint( QPainter::Antialiasing ); painter->setPen( opt.palette.color( QPalette::Text ) ); QRect r = option.rect.adjusted( 4, 4, -option.rect.width() + option.rect.height() - 4, -4 ); // painter->drawPixmap( r, QPixmap( RESPATH "images/cover-shadow.png" ) ); if ( !m_pixmaps.contains( index ) ) { if ( !item->album().isNull() ) { m_pixmaps.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->album(), r.size(), TomahawkUtils::Original, false ) ) ); _detail::Closure* closure = NewClosure( m_pixmaps[ index ], SIGNAL( repaintRequest() ), const_cast<TreeItemDelegate*>(this), SLOT( doUpdateIndex( const QPersistentModelIndex& ) ), QPersistentModelIndex( index ) ); closure->setAutoDelete( false ); } else if ( !item->artist().isNull() )
void PointItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QSpinBox *spinBox = qobject_cast<QSpinBox *>(editor); spinBox->setValue(index.data().toInt()); }
/*! Renders the delegate using the given \a painter and style \a option for the item specified by \a index. When reimplementing this function in a subclass, you should update the area held by the option's \l{QStyleOption::rect}{rect} variable, using the option's \l{QStyleOption::state}{state} variable to determine the state of the item to be displayed, and adjust the way it is painted accordingly. For example, a selected item may need to be displayed differently to unselected items, as shown in the following code: \snippet itemviews/pixelator/pixeldelegate.cpp 2 \dots After painting, you should ensure that the painter is returned to its the state it was supplied in when this function was called. For example, it may be useful to call QPainter::save() before painting and QPainter::restore() afterwards. \sa QStyle::State */ void QItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_D(const QItemDelegate); Q_ASSERT(index.isValid()); QStyleOptionViewItem opt = setOptions(index, option); // prepare painter->save(); if (d->clipPainting) painter->setClipRect(opt.rect); // get the data and the rectangles QVariant value; QPixmap pixmap; QRect decorationRect; value = index.data(Qt::DecorationRole); if (value.isValid()) { // ### we need the pixmap to call the virtual function pixmap = decoration(opt, value); if (value.type() == QVariant::Icon) { d->tmp.icon = qvariant_cast<QIcon>(value); d->tmp.mode = d->iconMode(option.state); d->tmp.state = d->iconState(option.state); const QSize size = d->tmp.icon.actualSize(option.decorationSize, d->tmp.mode, d->tmp.state); decorationRect = QRect(QPoint(0, 0), size); } else { d->tmp.icon = QIcon(); decorationRect = QRect(QPoint(0, 0), pixmap.size()); } } else { d->tmp.icon = QIcon(); decorationRect = QRect(); } QString text; QRect displayRect; value = index.data(Qt::DisplayRole); if (value.isValid() && !value.isNull()) { text = QItemDelegatePrivate::valueToText(value, opt); displayRect = textRectangle(painter, d->textLayoutBounds(opt), opt.font, text); } QRect checkRect; Qt::CheckState checkState = Qt::Unchecked; value = index.data(Qt::CheckStateRole); if (value.isValid()) { checkState = static_cast<Qt::CheckState>(value.toInt()); checkRect = doCheck(opt, opt.rect, value); } // do the layout doLayout(opt, &checkRect, &decorationRect, &displayRect, false); // draw the item drawBackground(painter, opt, index); drawCheck(painter, opt, checkRect, checkState); drawDecoration(painter, opt, decorationRect, pixmap); drawDisplay(painter, opt, displayRect, text); drawFocus(painter, opt, displayRect); // done painter->restore(); }
void AccountFactoryWrapperDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItemV4 opt = option; initStyleOption( &opt, index ); const int center = opt.rect.height() / 2 + opt.rect.top(); const int topIcon = center - ICON_SIZE/2; // draw the background const QWidget* w = opt.widget; QStyle* style = w ? w->style() : QApplication::style(); style->drawPrimitive( QStyle::PE_PanelItemViewItem, &opt, painter, w ); Account* acc = qobject_cast< Account* >( index.data( AccountFactoryWrapper::AccountRole ).value< QObject* >() ); Q_ASSERT( acc ); // Checkbox on left edge, then text const QRect checkRect( PADDING/4, PADDING/4 + opt.rect.top(), opt.rect.height() - PADDING/4, opt.rect.height() - PADDING/4 ); m_cachedCheckRects[ index ] = checkRect; QStyleOptionViewItemV4 opt2 = opt; opt2.rect = checkRect; opt.checkState == Qt::Checked ? opt2.state |= QStyle::State_On : opt2.state |= QStyle::State_Off; style->drawPrimitive( QStyle::PE_IndicatorViewItemCheck, &opt2, painter, w ); // name on left painter->drawText( opt.rect.adjusted( checkRect.right() + PADDING, PADDING, -PADDING, -PADDING ), Qt::AlignLeft | Qt::AlignVCenter, acc->accountFriendlyName() ); // remove, config, status on right const QRect pmRect( opt.rect.right() - PADDING - ICON_SIZE, topIcon, ICON_SIZE, ICON_SIZE ); painter->drawPixmap( pmRect, TomahawkUtils::defaultPixmap( TomahawkUtils::ListRemove, TomahawkUtils::Original, pmRect.size() ) ); m_cachedButtonRects[ index ] = pmRect; const QRect confRect( pmRect.left() - PADDING - CONFIG_WRENCH_SIZE, center - CONFIG_WRENCH_SIZE/2, CONFIG_WRENCH_SIZE, CONFIG_WRENCH_SIZE ); QStyleOptionToolButton topt; topt.rect = confRect; topt.pos = confRect.topLeft(); topt.font = opt.font; topt.icon = ImageRegistry::instance()->pixmap( RESPATH "images/configure.svg", QSize( CONFIG_WRENCH_SIZE - 8, CONFIG_WRENCH_SIZE - 8 ) ); topt.iconSize = QSize( CONFIG_WRENCH_SIZE - 8, CONFIG_WRENCH_SIZE - 8 ); topt.subControls = QStyle::SC_ToolButton; topt.activeSubControls = QStyle::SC_None; topt.features = QStyleOptionToolButton::None; bool pressed = ( m_configPressed == opt.index ); topt.state = pressed ? QStyle::State_On : QStyle::State_Raised; if( opt.state & QStyle::State_MouseOver || pressed ) topt.state |= QStyle::State_HasFocus; style->drawComplexControl( QStyle::CC_ToolButton, &topt, painter, w ); m_cachedConfigRects[ index ] = confRect; QPixmap p; QString statusText; Account::ConnectionState state = acc->connectionState(); const QRect connectIconRect( confRect.left() - PADDING - ICON_SIZE, topIcon, ICON_SIZE, ICON_SIZE ); if ( state == Account::Connected ) { p = TomahawkUtils::defaultPixmap( TomahawkUtils::SipPluginOnline, TomahawkUtils::Original, connectIconRect.size() ); statusText = tr( "Online" ); } else if ( state == Account::Connecting ) { p = TomahawkUtils::defaultPixmap( TomahawkUtils::SipPluginOffline, TomahawkUtils::Original, connectIconRect.size() ); statusText = tr( "Connecting..." ); } else { p = TomahawkUtils::defaultPixmap( TomahawkUtils::SipPluginOffline, TomahawkUtils::Original, connectIconRect.size() ); statusText = tr( "Offline" ); } painter->drawPixmap( connectIconRect, p ); int width = painter->fontMetrics().width( statusText ); painter->drawText( QRect( connectIconRect.left() - PADDING - width, center - painter->fontMetrics().height()/2, width, painter->fontMetrics().height() ), statusText ); }
void ComboBoxDelegate::testActivation(const QModelIndex &currIndex) { testActivation(currIndex.data().toString()); }
void GroupedIconView::LayoutItems() { if (!model()) return; const int count = model()->rowCount(); QString last_group; QPoint next_position(0, 0); int max_row_height = 0; visual_rects_.clear(); visual_rects_.reserve(count); headers_.clear(); for (int i=0 ; i<count ; ++i) { const QModelIndex index(model()->index(i, 0)); const QString group = index.data(Role_Group).toString(); const QSize size(rectForIndex(index).size()); // Is this the first item in a new group? if (group != last_group) { // Add the group header. Header header; header.y = next_position.y() + max_row_height + header_indent_; header.first_row = i; header.text = group; if (!last_group.isNull()) { header.y += header_spacing_; } headers_ << header; // Remember this group so we don't add it again. last_group = group; // Move the next item immediately below the header. next_position.setX(0); next_position.setY(header.y + header_height() + header_indent_ + header_spacing_); max_row_height = 0; } // Take into account padding and spacing QPoint this_position(next_position); if (this_position.x() == 0) { this_position.setX(this_position.x() + item_indent_); } else { this_position.setX(this_position.x() + spacing()); } // Should this item wrap? if (next_position.x() != 0 && this_position.x() + size.width() >= viewport()->width()) { next_position.setX(0); next_position.setY(next_position.y() + max_row_height); this_position = next_position; this_position.setX(this_position.x() + item_indent_); max_row_height = 0; } // Set this item's geometry visual_rects_.append(QRect(this_position, size)); // Update next index next_position.setX(this_position.x() + size.width()); max_row_height = qMax(max_row_height, size.height()); } verticalScrollBar()->setRange(0, next_position.y() + max_row_height - viewport()->height()); update(); }
void BigFirehoseDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { painter->save(); QColor bg; if (index.data( moose::CumulativeCountRole ).toInt() % 2 != index.row() % 2) { bg = option.palette.color( QPalette::AlternateBase ); painter->fillRect( option.rect, bg ); } else bg = option.palette.color( QPalette::Base ); QTransform t; QPoint p = option.rect.topLeft(); t.translate( p.x(), p.y() ); painter->setTransform( t ); const int S = painter->fontMetrics().lineSpacing(); QColor const primary = Qt::black; QColor const secondary = QColor(AGING_MOOSE); QPixmap px = index.data( Qt::DecorationRole ).value<QPixmap>(); const int n = option.rect.height() - 20; px = fitInSquare( px, n ); painter->drawPixmap( 10, 10, px ); painter->setPen( secondary ); painter->setBrush( Qt::NoBrush ); painter->drawRect( 10, 10, n, n ); // keep text within the rects we drew QRect r( 5, 5, option.rect.width() - 10, option.rect.height() - 10 ); //painter->setClipRect( r ); painter->drawText( m_metric, 5 + S + 2 + S, index.data( moose::SecondaryDisplayRole ).toString() ); QFont f = painter->font(); f.setBold( true ); painter->setFont( f ); painter->setPen( primary ); painter->drawText( m_metric, 5 + S, index.data().toString() ); QString const small = index.data( moose::SmallDisplayRole ).toString(); if (small.size()) { int const h = painter->fontMetrics().height(); int const w_name = painter->fontMetrics().width( index.data().toString() ); f.setPointSize( 8 ); f.setBold( false ); painter->setFont( f ); int const w = painter->fontMetrics().width( small ); QRect const r_text_bounds( option.rect.width() - 5 - w, 10, w, h ); QRect const r_text = r_text_bounds.adjusted( -5, 0, 0, 0 ); QRect r_g = r_text; r_g.translate( -10, 0 ); r_g.setWidth( 10 ); if (m_metric + w_name > r_text.left()) { QLinearGradient g( r_g.topLeft(), r_g.topRight() ); g.setColorAt( 0, Qt::transparent ); g.setColorAt( 1, bg ); painter->fillRect( r_text, bg ); painter->fillRect( r_g, g ); } painter->setPen( secondary ); painter->drawText( r_text_bounds, Qt::AlignVCenter | Qt::AlignRight, small ); } QRect r3( option.rect.right() - 14, 5 + S + 2, 15, 2*S ); QLinearGradient g( r3.topLeft(), r3.topRight() ); g.setColorAt( 0, Qt::transparent ); g.setColorAt( 0.9, bg ); painter->fillRect( r3, g ); painter->restore(); }
void NetworkActivityWidget::onPlaylistActivated( const QModelIndex& item ) { Tomahawk::playlist_ptr pl = item.data( RecentlyPlayedPlaylistsModel::PlaylistRole ).value< Tomahawk::playlist_ptr >(); ViewManager::instance()->show( pl ); }
void slideShowEngine::start() { int x,y; QPixmap pix; QModelIndex index; QVariant val; node itemNode; QPropertyAnimation *enterAnimation,*displayAnimation,*exitAnimation; Pixmap *item; effect e; QParallelAnimationGroup *parallelAnim; QSequentialAnimationGroup *seqAnim; if(m_groupAnimation->state()==QAbstractAnimation::Paused) resume(); if(m_groupAnimation->state()==QAbstractAnimation::Running) return; QList <QGraphicsView *> views=m_scene->views(); m_size=views.at(0)->size(); m_scene->clear(); for(int i=0;i<m_sequence->rowCount();i++) { index=m_sequence->index(i); if(index.isValid()) { m_scene->setSceneRect(0.0,0.0,qreal(m_size.width()),qreal(m_size.height())); // come fare per full screen size? qDebug() << "index valid"; val=index.data(Qt::UserRole); itemNode=val.value<node>(); qDebug() << "pix:" << itemNode.nodeName(); pix=itemNode.nodePixmap(); if(pix.width()>m_size.width() || pix.height()>m_size.height()) pix=pix.scaled(m_size,Qt::KeepAspectRatio,Qt::SmoothTransformation); item = new Pixmap(pix); m_PixmapList.append(item); // serve questa lista? if(m_size.width()>pix.width()) { x=(m_size.width()-pix.width())/2; } else { x=0; } if(m_size.height()>pix.height()) { y=(m_size.height()-pix.height())/2; } else { y=0; } item->setPos(qreal(x), qreal(y)); qDebug() <<qreal(m_sequence->rowCount()-i); item->setZValue(qreal(m_sequence->rowCount()-i)); //m_scene->addItem(item); e=itemNode.enterEffect(); enterAnimation = new QPropertyAnimation(item, e.effectType().toAscii()); itemNode.setEnterAnimation(enterAnimation,item); connect(enterAnimation,SIGNAL(finished()),this,SLOT(animEnterFinished())); e=itemNode.displayEffect(); displayAnimation = new QPropertyAnimation(item, e.effectType().toAscii()); itemNode.setDisplayAnimation(displayAnimation,item); connect(displayAnimation,SIGNAL(finished()),this,SLOT(animDisplayFinished())); e=itemNode.exitEffect(); exitAnimation = new QPropertyAnimation(item, e.effectType().toAscii()); itemNode.setExitAnimation(exitAnimation,item); connect(exitAnimation,SIGNAL(finished()),this,SLOT(animExitFinished())); //parallelAnim= new QParallelAnimationGroup; //parallelAnim->addAnimation(exitAnimation); seqAnim = new QSequentialAnimationGroup; seqAnim->addAnimation(enterAnimation); seqAnim->addAnimation(displayAnimation); seqAnim->addAnimation(exitAnimation); qDebug() << "add all animation"; m_groupAnimation->addAnimation(seqAnim); connect(m_groupAnimation,SIGNAL(finished()),this,SLOT(endOfSlideShow())); //group->addAnimation(animation4); } // end index is valid } // end for qDebug() << "start group"; m_currentSlideIndex=0; m_scene->addItem(m_PixmapList.at(m_currentSlideIndex)); m_groupAnimation->start(); //m_timerId=startTimer(2); //m_slideShowClock.restart(); int width=640; int height=480; int bitrate=1000000; int gop = 20; // Create the encoder //QVideoEncoder encoder; //encoder.createFile("test.avi",width,height,bitrate,gop); }
void PlaylistView::drawRow(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItemV4 opt(option); bool is_current = index.data(Playlist::Role_IsCurrent).toBool(); bool is_paused = index.data(Playlist::Role_IsPaused).toBool(); if (is_current) { const_cast<PlaylistView*>(this)->last_current_item_ = index; const_cast<PlaylistView*>(this)->last_glow_rect_ = opt.rect; int step = glow_intensity_step_; if (step >= kGlowIntensitySteps) step = 2 * (kGlowIntensitySteps - 1) - step + 1; int row_height = opt.rect.height(); if (row_height != row_height_) { // Recreate the pixmaps if the height changed since last time const_cast<PlaylistView*>(this)->row_height_ = row_height; const_cast<PlaylistView*>(this)->ReloadBarPixmaps(); } QRect middle(opt.rect); middle.setLeft(middle.left() + currenttrack_bar_left_[0].width()); middle.setRight(middle.right() - currenttrack_bar_right_[0].width()); // Selection if (selectionModel()->isSelected(index)) painter->fillRect(opt.rect, opt.palette.color(QPalette::Highlight)); // Draw the bar painter->drawPixmap(opt.rect.topLeft(), currenttrack_bar_left_[step]); painter->drawPixmap( opt.rect.topRight() - currenttrack_bar_right_[0].rect().topRight(), currenttrack_bar_right_[step]); painter->drawPixmap(middle, currenttrack_bar_mid_[step]); // Draw the play icon QPoint play_pos(currenttrack_bar_left_[0].width() / 3 * 2, (row_height - currenttrack_play_.height()) / 2); painter->drawPixmap(opt.rect.topLeft() + play_pos, is_paused ? currenttrack_pause_ : currenttrack_play_); // Set the font opt.palette.setColor(QPalette::Text, QApplication::palette().color( QPalette::HighlightedText)); opt.palette.setColor(QPalette::Highlight, Qt::transparent); opt.palette.setColor(QPalette::AlternateBase, Qt::transparent); opt.decorationSize = QSize(20, 20); // Draw the actual row data on top. We cache this, because it's fairly // expensive (1-2ms), and we do it many times per second. const bool cache_dirty = cached_current_row_rect_ != opt.rect || cached_current_row_row_ != index.row() || cached_current_row_.isNull(); // We can't update the cache if we're not drawing the entire region, // QTreeView clips its drawing to only the columns in the region, so it // wouldn't update the whole pixmap properly. const bool whole_region = current_paint_region_.boundingRect().width() == viewport()->width(); if (!cache_dirty) { painter->drawPixmap(opt.rect, cached_current_row_); } else { if (whole_region) { const_cast<PlaylistView*>(this) ->UpdateCachedCurrentRowPixmap(opt, index); painter->drawPixmap(opt.rect, cached_current_row_); } else { QTreeView::drawRow(painter, opt, index); } } } else { QTreeView::drawRow(painter, opt, index); } }
void MixxxLibraryFeature::activateChild(const QModelIndex& index) { QString itemName = index.data().toString(); emit(switchToView(itemName)); emit(enableCoverArtDisplay(true)); }
void RoutingLayerPrivate::renderRoute( GeoPainter *painter ) { GeoDataLineString waypoints = m_routingModel->route().path(); QPen standardRoutePen( m_marbleWidget->model()->routingManager()->routeColorStandard() ); standardRoutePen.setWidth( 5 ); if ( m_routeDirty ) { standardRoutePen.setStyle( Qt::DotLine ); } painter->setPen( standardRoutePen ); painter->drawPolyline( waypoints ); if ( m_viewportChanged && m_viewContext == Still ) { int const offset = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen ? 24 : 8; m_routeRegion = painter->regionFromPolyline( waypoints, offset ); } standardRoutePen.setWidth( 2 ); painter->setPen( standardRoutePen ); // Map matched position //painter->setBrush( QBrush( Oxygen::brickRed4) ); //painter->drawEllipse( m_routingModel->route().positionOnRoute(), 8, 8 ); painter->setBrush( QBrush( m_marbleWidget->model()->routingManager()->routeColorAlternative() ) ); if ( !m_dropStopOver.isNull() ) { int dx = 1 + m_pixmapSize.width() / 2; int dy = 1 + m_pixmapSize.height() / 2; QPoint center = m_dropStopOver - QPoint( dx, dy ); painter->drawPixmap( center, m_targetPixmap ); if ( !m_dragStopOver.isNull() && m_dragStopOverRightIndex >= 0 && m_dragStopOverRightIndex <= m_routeRequest->size() ) { QPoint moved = m_dropStopOver - m_dragStopOver; if ( moved.manhattanLength() > 10 ) { qreal lon( 0.0 ), lat( 0.0 ); if ( m_marbleWidget->geoCoordinates( m_dropStopOver.x(), m_dropStopOver.y(), lon, lat, GeoDataCoordinates::Radian ) ) { GeoDataCoordinates drag( lon, lat ); standardRoutePen.setStyle( Qt::DotLine ); painter->setPen( standardRoutePen ); GeoDataLineString lineString; if ( m_dragStopOverRightIndex > 0 ) { lineString << m_routeRequest->at( m_dragStopOverRightIndex-1 ); } lineString << drag; if ( m_dragStopOverRightIndex < m_routeRequest->size() ) { lineString << m_routeRequest->at( m_dragStopOverRightIndex ); } painter->drawPolyline( lineString ); standardRoutePen.setStyle( Qt::SolidLine ); painter->setPen( standardRoutePen ); } } } } if ( m_viewContext == Animation ) { return; } m_instructionRegions.clear(); for ( int i = 0; i < m_routingModel->rowCount(); ++i ) { QModelIndex index = m_routingModel->index( i, 0 ); GeoDataCoordinates pos = qVariantValue<GeoDataCoordinates>( index.data( MarblePlacemarkModel::CoordinateRole ) ); painter->setBrush( QBrush( m_marbleWidget->model()->routingManager()->routeColorAlternative() ) ); if ( m_selectionModel && m_selectionModel->selection().contains( index ) ) { for ( int j=0; j<m_routingModel->route().size(); ++j ) { const RouteSegment & segment = m_routingModel->route().at( j ); if ( segment.maneuver().position() == pos ) { GeoDataLineString currentRoutePoints = segment.path(); QPen activeRouteSegmentPen( m_marbleWidget->model()->routingManager()->routeColorHighlighted() ); activeRouteSegmentPen.setWidth( 6 ); if ( m_routeDirty ) { activeRouteSegmentPen.setStyle( Qt::DotLine ); } painter->setPen( activeRouteSegmentPen ); painter->drawPolyline( currentRoutePoints ); painter->setPen( standardRoutePen ); painter->setBrush( QBrush( alphaAdjusted( Oxygen::hotOrange4, 200 ) ) ); } } } QRegion region = painter->regionFromEllipse( pos, 12, 12 ); m_instructionRegions.push_front( ModelRegion( index, region ) ); painter->drawEllipse( pos, 6, 6 ); if( !m_routingModel->deviatedFromRoute() ) { GeoDataCoordinates location = m_routingModel->route().currentSegment().nextRouteSegment().maneuver().position(); QString nextInstruction = m_routingModel->route().currentSegment().nextRouteSegment().maneuver().instructionText(); if( !nextInstruction.isEmpty() ) { painter->setBrush( QBrush( Oxygen::hotOrange4 ) ); painter->drawEllipse( location, 6, 6 ); } } } }
void SearchItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem opt(option); QStyle *style = opt.widget->style(); // Find decoration roles with data present. QList<int> roles; for (int role : m_decorationRoles) { if (!index.data(role).isNull()) roles.append(role); } /// TODO: Implemented via initStyleOption() overload if (!roles.isEmpty()) { opt.features |= QStyleOptionViewItem::HasDecoration; opt.icon = index.data(roles.first()).value<QIcon>(); const QSize actualSize = opt.icon.actualSize(opt.decorationSize); opt.decorationSize = {std::min(opt.decorationSize.width(), actualSize.width()), std::min(opt.decorationSize.height(), actualSize.height())}; } style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); const int margin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, &opt, opt.widget) + 1; if (!roles.isEmpty()) { QIcon::Mode mode = QIcon::Normal; if (!(opt.state & QStyle::State_Enabled)) mode = QIcon::Disabled; else if (opt.state & QStyle::State_Selected) mode = QIcon::Selected; const QIcon::State state = opt.state & QStyle::State_Open ? QIcon::On : QIcon::Off; // All icons are sized after the first one. QRect iconRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt, opt.widget); const int dx = iconRect.width() + margin; for (int i = 1; i < roles.size(); ++i) { opt.decorationSize.rwidth() += dx; iconRect.translate(dx, 0); const QIcon icon = index.data(roles[i]).value<QIcon>(); icon.paint(painter, iconRect, opt.decorationAlignment, mode, state); } } // Match QCommonStyle behaviour. const QString text = index.data().toString(); const QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, opt.widget) .adjusted(margin, 0, -margin, 0); const QFontMetrics &fm = opt.fontMetrics; const QString elidedText = fm.elidedText(text, opt.textElideMode, textRect.width()); if (!m_highlight.isEmpty()) { painter->save(); painter->setRenderHint(QPainter::Antialiasing); painter->setPen(QColor::fromRgb(255, 253, 0)); const QColor highlightColor = opt.state & (QStyle::State_Selected | QStyle::State_HasFocus) ? QColor::fromRgb(255, 255, 100, 20) : QColor::fromRgb(255, 255, 100, 120); for (int i = 0;;) { const int matchIndex = text.indexOf(m_highlight, i, Qt::CaseInsensitive); if (matchIndex == -1 || matchIndex >= elidedText.length() - 1) break; QRect highlightRect = textRect.adjusted(fm.width(elidedText.left(matchIndex)), 2, 0, -2); highlightRect.setWidth(fm.width(elidedText.mid(matchIndex, m_highlight.length()))); QPainterPath path; path.addRoundedRect(highlightRect, 2, 2); painter->fillPath(path, highlightColor); painter->drawPath(path); i = matchIndex + m_highlight.length(); } painter->restore(); } painter->save(); #ifdef Q_OS_WIN32 // QWindowsVistaStyle overrides highlight colour. if (style->objectName() == QStringLiteral("windowsvista")) { opt.palette.setColor(QPalette::All, QPalette::HighlightedText, opt.palette.color(QPalette::Active, QPalette::Text)); } #endif const QPalette::ColorGroup cg = opt.state & QStyle::State_Active ? QPalette::Normal : QPalette::Inactive; if (opt.state & QStyle::State_Selected) painter->setPen(opt.palette.color(cg, QPalette::HighlightedText)); else painter->setPen(opt.palette.color(cg, QPalette::Text)); // Vertically align the text in the middle to match QCommonStyle behaviour. const QRect alignedRect = QStyle::alignedRect(opt.direction, opt.displayAlignment, QSize(1, fm.height()), textRect); painter->drawText(QPoint(alignedRect.x(), alignedRect.y() + fm.ascent()), elidedText); painter->restore(); }
bool CQSpecieDM::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && role == Qt::EditRole) { bool defaultRow = isDefaultRow(index); if (defaultRow) { if (index.column() == COL_TYPE_SPECIES) { if (index.data().toString() == QString(FROM_UTF8(CModelEntity::StatusName[mItemToType[value.toInt()]]))) return false; } else if (index.column() == COL_COMPARTMENT && value == "") { return false; } else if (index.data() == value) { return false; } mNotify = false; insertRow(); mNotify = true; } else { assert(CCopasiRootContainer::getDatamodelList()->size() > 0); mpSpecies = (*CCopasiRootContainer::getDatamodelList())[0]->getModel()->getMetabolites()[index.row()]; } const CCompartment * pCompartment = NULL; if (index.column() == COL_COMPARTMENT || index.column() == COL_ICONCENTRATION || index.column() == COL_INUMBER) { try { pCompartment = mpSpecies->getCompartment(); } catch (...) {} } if (index.column() == COL_NAME_SPECIES) mpSpecies->setObjectName(TO_UTF8(value.toString())); else if (index.column() == COL_COMPARTMENT) { // This must be set first for setInitialConcentration and // setInitialNumber to work correctly. std::string Compartment(TO_UTF8(value.toString())); if (Compartment != pCompartment->getObjectName()) { std::string CompartmentToRemove = mpSpecies->getCompartment()->getObjectName(); assert(CCopasiRootContainer::getDatamodelList()->size() > 0); if (!(*CCopasiRootContainer::getDatamodelList())[0]->getModel()->getCompartments()[Compartment]->addMetabolite(mpSpecies)) { QString msg; msg = "Unable to move species '" + FROM_UTF8(mpSpecies->getObjectName()) + "'\n" + "from compartment '" + FROM_UTF8(CompartmentToRemove) + "' to compartment '" + FROM_UTF8(Compartment) + "'\n" + "since a species with that name already exist in the target compartment."; CQMessageBox::information(NULL, "Unable to move Species", msg, QMessageBox::Ok, QMessageBox::Ok); return false; } else { (*CCopasiRootContainer::getDatamodelList())[0]->getModel()->getCompartments()[CompartmentToRemove]->getMetabolites().remove(mpSpecies->getObjectName()); (*CCopasiRootContainer::getDatamodelList())[0]->getModel()->setCompileFlag(); (*CCopasiRootContainer::getDatamodelList())[0]->getModel()->initializeMetabolites(); if (mpSpecies && pCompartment) { C_FLOAT64 Factor = 1.0 / pCompartment->getInitialValue(); Factor *= pCompartment->getInitialValue(); mpSpecies->setInitialValue(Factor * this->index(index.row(), COL_INUMBER).data().toDouble()); mpSpecies->setValue(Factor * this->index(index.row(), COL_NUMBER).data().toDouble()); } emit notifyGUI(ListViews::METABOLITE, ListViews::CHANGE, mpSpecies->getKey()); emit notifyGUI(ListViews::COMPARTMENT, ListViews::CHANGE, pCompartment->getKey()); } } } else if (index.column() == COL_TYPE_SPECIES) mpSpecies->setStatus((CModelEntity::Status) mItemToType[value.toInt()]); else if (index.column() == COL_ICONCENTRATION) { if (mFlagConc) mpSpecies->setInitialConcentration(value.toDouble()); if (mpSpecies && pCompartment) { const C_FLOAT64 initialValue = CMetab::convertToNumber(this->index(index.row(), COL_ICONCENTRATION).data().toDouble(), *pCompartment, *(*CCopasiRootContainer::getDatamodelList())[0]->getModel()); mpSpecies->setInitialValue(initialValue); } } else if (index.column() == COL_INUMBER) { if (!mFlagConc) mpSpecies->setInitialValue(value.toDouble()); if (mpSpecies && pCompartment) { mpSpecies->setInitialConcentration( CMetab::convertToConcentration(this->index(index.row(), COL_INUMBER).data().toDouble(), *pCompartment, *(*CCopasiRootContainer::getDatamodelList())[0]->getModel()) ); } } if (defaultRow && this->index(index.row(), COL_NAME_SPECIES).data().toString() == "species") mpSpecies->setObjectName(TO_UTF8(createNewName("species", COL_NAME_SPECIES))); //Save Key std::string key = mpSpecies->getKey(); emit dataChanged(index, index); if (defaultRow) { emit notifyGUI(ListViews::METABOLITE, ListViews::ADD, key); } else { emit notifyGUI(ListViews::METABOLITE, ListViews::CHANGE, key); } } return true; }
void ChangesDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (!index.isValid()) { return; } bool leftToRight = (painter->layoutDirection() == Qt::LeftToRight); QStyleOptionViewItemV4 opt(option); QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); painter->save(); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget); painter->restore(); //grab the package from the index pointer QString pkgName = index.data(PackageModel::NameRole).toString(); QString pkgSummary = index.data(PackageModel::SummaryRole).toString(); QString pkgVersion = index.data(PackageModel::VersionRole).toString(); QString pkgArch = index.data(PackageModel::ArchRole).toString(); // QString pkgIconPath = index.data(PackageModel::IconPathRole).toString(); bool pkgChecked = index.data(PackageModel::CheckStateRole).toBool(); bool pkgCheckable = !index.data(Qt::CheckStateRole).isNull(); Transaction::Info info; info = index.data(PackageModel::InfoRole).value<Transaction::Info>(); bool pkgInstalled = (info == Transaction::InfoInstalled || info == Transaction::InfoCollectionInstalled); bool pkgCollection = (info == Transaction::InfoCollectionInstalled || info == Transaction::InfoCollectionAvailable); QIcon emblemIcon; if (pkgCheckable) { // update kind icon emblemIcon = index.data(PackageModel::IconRole).value<QIcon>(); } else { emblemIcon = m_checkedIcon; } // pain the background (checkbox and the extender) if (m_extendPixmapWidth) { KExtendableItemDelegate::paint(painter, opt, index); } int leftCount; if (leftToRight) { opt.rect.setLeft(option.rect.left() + m_extendPixmapWidth + UNIVERSAL_PADDING); leftCount = opt.rect.left() + UNIVERSAL_PADDING; } else { opt.rect.setRight(option.rect.right() - m_extendPixmapWidth - UNIVERSAL_PADDING); leftCount = opt.rect.width() - (UNIVERSAL_PADDING + MAIN_ICON_SIZE); } int left = opt.rect.left(); int top = opt.rect.top(); int width = opt.rect.width(); QStyleOptionButton optBt; optBt.rect = opt.rect; if (pkgCheckable) { optBt.rect = style->subElementRect(QStyle::SE_CheckBoxIndicator, &optBt); // Count the checkbox size if (leftToRight) { leftCount += optBt.rect.width(); } else { leftCount -= optBt.rect.width(); } } else if ((option.state & QStyle::State_MouseOver) || (option.state & QStyle::State_Selected) || !pkgChecked) { if (leftToRight) { optBt.rect.setLeft(left + width - (m_buttonSize.width() + UNIVERSAL_PADDING)); width -= m_buttonSize.width() + UNIVERSAL_PADDING; } else { optBt.rect.setLeft(left + UNIVERSAL_PADDING); left += m_buttonSize.width() + UNIVERSAL_PADDING; } // Calculate the top of the button which is the item height - the button height size divided by 2 // this give us a little value which is the top and bottom margin optBt.rect.setTop(optBt.rect.top() + ((calcItemHeight(option) - m_buttonSize.height()) / 2)); optBt.rect.setSize(m_buttonSize); // the width and height sizes of the button optBt.features = QStyleOptionButton::Flat; optBt.iconSize = m_buttonIconSize; optBt.icon = pkgInstalled ? m_removeIcon : m_installIcon; optBt.text = pkgInstalled ? m_removeString : m_installString; if (pkgChecked) { optBt.state |= QStyle::State_Raised | QStyle::State_Active | QStyle::State_Enabled;; } else { if ((option.state & QStyle::State_MouseOver) && !(option.state & QStyle::State_Selected)) { optBt.state |= QStyle::State_MouseOver; } optBt.state |= QStyle::State_Sunken | QStyle::State_Active | QStyle::State_Enabled; } style->drawControl(QStyle::CE_PushButton, &optBt, painter); } // QAbstractItemView *view = qobject_cast<QAbstractItemView*>(parent()); // QPoint pos = view->viewport()->mapFromGlobal(QCursor::pos()); // kDebug() << pos; // selects the mode to paint the icon based on the info field QIcon::Mode iconMode = QIcon::Normal; if (option.state & QStyle::State_MouseOver) { iconMode = QIcon::Active; } QColor foregroundColor = (option.state.testFlag(QStyle::State_Selected))? option.palette.color(QPalette::HighlightedText):option.palette.color(QPalette::Text); // Painting main column QStyleOptionViewItem local_option_title(option); QStyleOptionViewItem local_option_normal(option); local_option_normal.font.setPointSize(local_option_normal.font.pointSize() - 1); QPixmap pixmap(option.rect.size()); pixmap.fill(Qt::transparent); QPainter p(&pixmap); p.translate(-option.rect.topLeft()); // Main icon QIcon icon; if (pkgCollection) { icon = m_collectionIcon; } else { icon = PkIcons::getIcon(index.data(PackageModel::IconRole).toString(), QString()); if (icon.isNull()) { icon = m_packageIcon; } } // if (pkgIconPath.isEmpty()) { // icon = pkgCollection ? m_collectionIcon : m_packageIcon; // } else { // icon = PkIcons::getIcon(pkgIconPath, "package"); // } int iconSize = calcItemHeight(option) - 2 * UNIVERSAL_PADDING; icon.paint(&p, leftCount, top + UNIVERSAL_PADDING, iconSize, iconSize, Qt::AlignCenter, iconMode); int textWidth; if (leftToRight) { // add the main icon leftCount += iconSize + UNIVERSAL_PADDING; textWidth = width - (leftCount - left); } else { leftCount -= UNIVERSAL_PADDING; textWidth = leftCount - left; leftCount = left; } // Painting // Text const int itemHeight = calcItemHeight(option); p.setPen(foregroundColor); // compose the top line // Collections does not have version and arch if (option.state & QStyle::State_MouseOver && !pkgCollection) { //! pkgName = pkgName + " - " + pkgVersion + (pkgArch.isNull() ? NULL : " (" + pkgArch + ')'); } // draw the top line int topTextHeight = QFontInfo(local_option_title.font).pixelSize(); p.setFont(local_option_title.font); p.drawText(leftCount, top, textWidth, topTextHeight + UNIVERSAL_PADDING, Qt::AlignVCenter | Qt::AlignLeft, pkgName); // draw the bottom line iconSize = topTextHeight + UNIVERSAL_PADDING; if (pkgCheckable || pkgInstalled) { emblemIcon.paint(&p, leftToRight ? leftCount : (textWidth + left) - iconSize, top + topTextHeight + UNIVERSAL_PADDING, iconSize, iconSize, Qt::AlignVCenter | Qt::AlignHCenter, iconMode); } // store the original opacity qreal opa = p.opacity(); if (!(option.state & QStyle::State_MouseOver) && !(option.state & QStyle::State_Selected)) { p.setOpacity(opa / 2.5); } p.setFont(local_option_normal.font); p.drawText(leftToRight ? leftCount + iconSize + UNIVERSAL_PADDING : left - UNIVERSAL_PADDING, top + itemHeight / 2, textWidth - iconSize, QFontInfo(local_option_normal.font).pixelSize() + UNIVERSAL_PADDING, Qt::AlignTop | Qt::AlignLeft, pkgSummary); p.setOpacity(opa); QLinearGradient gradient; // Gradient part of the background - fading of the text at the end if (leftToRight) { gradient = QLinearGradient(left + width - UNIVERSAL_PADDING - FADE_LENGTH, 0, left + width - UNIVERSAL_PADDING, 0); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, Qt::transparent); } else { gradient = QLinearGradient(left + UNIVERSAL_PADDING, 0, left + UNIVERSAL_PADDING + FADE_LENGTH, 0); gradient.setColorAt(0, Qt::transparent); gradient.setColorAt(1, Qt::white); } QRect paintRect = option.rect; p.setCompositionMode(QPainter::CompositionMode_DestinationIn); p.fillRect(paintRect, gradient); if (leftToRight) { gradient.setStart(left + width - (UNIVERSAL_PADDING + EMBLEM_ICON_SIZE) - FADE_LENGTH, 0); gradient.setFinalStop(left + width - (UNIVERSAL_PADDING + EMBLEM_ICON_SIZE), 0); } else { gradient.setStart(left + UNIVERSAL_PADDING + (UNIVERSAL_PADDING + EMBLEM_ICON_SIZE), 0); gradient.setFinalStop(left + UNIVERSAL_PADDING + (UNIVERSAL_PADDING + EMBLEM_ICON_SIZE) + FADE_LENGTH, 0); } paintRect.setHeight(UNIVERSAL_PADDING + MAIN_ICON_SIZE / 2); p.fillRect(paintRect, gradient); p.setCompositionMode(QPainter::CompositionMode_SourceOver); p.end(); painter->drawPixmap(option.rect.topLeft(), pixmap); }
void ScenarioReviewItemDelegate::paint(QPainter* _painter, const QStyleOptionViewItem& _option, const QModelIndex& _index) const { // // Получим настройки стиля // QStyleOptionViewItem opt = _option; initStyleOption(&opt, _index); // // Рисуем ручками // _painter->save(); _painter->setRenderHint(QPainter::Antialiasing, true); // // Определим кисти и шрифты // QColor backgroundColor = opt.palette.base().color(); QColor replyBackgroundColor = opt.palette.alternateBase().color(); QColor borderColor = opt.palette.midlight().color(); QColor textColor = opt.palette.windowText().color(); QColor replyColor = opt.palette.windowText().color(); QColor dateColor = opt.palette.dark().color(); QFont headerFont = opt.font; headerFont.setBold(true); QFont dateFont = opt.font; dateFont.setBold(true); #ifdef Q_OS_WIN dateFont.setPointSize(dateFont.pointSize() - 1); #else dateFont.setPointSize(dateFont.pointSize() - 4); #endif QFont textFont = QApplication::font(); // // ... для выделенных элементов // if (opt.state.testFlag(QStyle::State_Selected)) { backgroundColor = opt.palette.highlight().color(); textColor = opt.palette.highlightedText().color(); } // // Рисуем // const int HEADER_LINE_HEIGHT = QFontMetrics(headerFont).height(); const int DATE_LINE_HEIGHT = QFontMetrics(dateFont).height(); // // Меняем координаты, чтобы рисовать было удобнее // _painter->translate(opt.rect.topLeft()); // // Определим данные // const bool done = _index.data(ScenarioReviewModel::IsDoneRole).toBool(); QStringList authors = _index.data(ScenarioReviewModel::CommentsAuthorsRole).toStringList(); const QStringList dates = _index.data(ScenarioReviewModel::CommentsDatesRole).toStringList(); const QStringList comments = _index.data(ScenarioReviewModel::CommentsRole).toStringList(); // // ... если не задано ни одного автора, то эмулируем одного, для формирования пустой строки // if (authors.isEmpty()) { authors.append(""); } // // Для каждого комментария // int width = _option.widget->width(); if (const QAbstractItemView* view = qobject_cast<const QAbstractItemView*>(_option.widget)) { width = view->viewport()->width(); } const int headerHeight = TOP_MARGIN + _option.fontMetrics.height() * 2 + BOTTOM_MARGIN; int lastTop = 0; for (int commentIndex = 0; commentIndex < authors.size(); ++commentIndex) { // // Определим область комментария // int height = headerHeight; if (!done) { height += ::commentHeightForWidth(comments.value(commentIndex), width) + SPACING; } const QRect rect(0, lastTop, width, height); // // ... фон // _painter->fillRect(rect, commentIndex == 0 ? backgroundColor : replyBackgroundColor); // // ... цвет заметки // const QColor color = _index.data(Qt::DecorationRole).value<QColor>(); const QRect colorRect(0, lastTop, COLOR_MARK_WIDTH, height); _painter->fillRect(colorRect, commentIndex == 0 ? color : replyBackgroundColor); // // ... границы // _painter->setPen(borderColor); _painter->drawRect(rect); // // ... автор // _painter->setPen(commentIndex == 0 ? textColor : replyColor); _painter->setFont(headerFont); const QRect headerRect( colorRect.right() + SPACING, lastTop + TOP_MARGIN, width - colorRect.right() - SPACING - RIGHT_MARGIN, HEADER_LINE_HEIGHT ); _painter->drawText(headerRect, authors.value(commentIndex)); // // ... дата // _painter->setPen(dateColor); _painter->setFont(dateFont); const QRect dateRect( colorRect.right() + SPACING, headerRect.bottom(), width - colorRect.right() - SPACING - RIGHT_MARGIN, DATE_LINE_HEIGHT ); const QString date = QDateTime::fromString(dates.value(commentIndex), Qt::ISODate).toString("dd.MM.yyyy hh:mm"); _painter->drawText(dateRect, date); // // ... если комментарий исправлен на этом месте завершаем рисование // if (done) { break; } // // ... комментарий // _painter->setPen(commentIndex == 0 ? textColor : replyColor); _painter->setFont(textFont); const QRect commentRect( colorRect.right() + SPACING, dateRect.bottom() + SPACING, width - colorRect.right() - SPACING - RIGHT_MARGIN, height - headerHeight - SPACING ); _painter->drawText(commentRect, Qt::TextWordWrap, comments.value(commentIndex)); lastTop += height; } _painter->restore(); }
void ListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QRect r = option.rect; //Color: #C4C4C4 QPen linePen(QColor::fromRgb(211, 211, 211), 2, Qt::SolidLine); //Color: #005A83 QPen lineMarkedPen(QColor::fromRgb(0, 90, 131), 1, Qt::SolidLine); //Color: #333 QPen fontPen(QColor::fromRgb(51, 51, 51), 1, Qt::SolidLine); //Color: #fff QPen fontMarkedPen(Qt::white, 1, Qt::SolidLine); //BORDER painter->setPen(linePen); painter->drawLine(r.topLeft(), r.topRight()); painter->drawLine(r.topRight(), r.bottomRight()); painter->drawLine(r.bottomLeft(), r.bottomRight()); painter->drawLine(r.topLeft(), r.bottomLeft()); if(option.state & QStyle::State_Selected) { QLinearGradient gradientSelected(r.left(), r.top(), r.left(), r.height() + r.top()); gradientSelected.setColorAt(0.0, QColor::fromRgb(119, 213, 247)); gradientSelected.setColorAt(0.9, QColor::fromRgb(27, 134, 183)); gradientSelected.setColorAt(1.0, QColor::fromRgb(0, 120, 174)); painter->setBrush(gradientSelected); painter->drawRect(r); //BORDER painter->setPen(lineMarkedPen); painter->drawLine(r.topLeft(), r.topRight()); painter->drawLine(r.topRight(), r.bottomRight()); painter->drawLine(r.bottomLeft(), r.bottomRight()); painter->drawLine(r.topLeft(), r.bottomLeft()); painter->setPen(fontMarkedPen); } else { //BACKGROUND //ALTERNATING COLORS painter->setBrush((index.row() % 2) ? Qt::white : QColor(252, 252, 252)); painter->drawRect(r); //BORDER painter->setPen(linePen); painter->drawLine(r.topLeft(), r.topRight()); painter->drawLine(r.topRight(), r.bottomRight()); painter->drawLine(r.bottomLeft(), r.bottomRight()); painter->drawLine(r.topLeft(), r.bottomLeft()); painter->setPen(fontPen); } //GET TITLE, DESCRIPTION AND ICON QIcon ic = QIcon(qvariant_cast<QPixmap>(index.data(Qt::DecorationRole))); QString title = index.data(Qt::DisplayRole).toString(); QString description = index.data(CP_DESC_ROLE).toString(); int imageSpace = 10; if(!ic.isNull()) { //ICON r = option.rect.adjusted(5, 10, -10, -10); ic.paint(painter, r, Qt::AlignVCenter | Qt::AlignLeft); imageSpace = 80; } //TITLE r = option.rect.adjusted(imageSpace, 0, -10, -30); painter->setFont(QFont("Lucida Grande", PGEDefaultFontSize + 2, QFont::Bold)); painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignBottom | Qt::AlignLeft, title, &r); //DESCRIPTION r = option.rect.adjusted(imageSpace, 30, -10, 30); painter->setFont(QFont("Lucida Grande", PGEDefaultFontSize, QFont::Normal)); painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignLeft, description, &r); }
void QFontFamilyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QString text = index.data(Qt::DisplayRole).toString(); QFont font(option.font); font.setPointSize(QFontInfo(font).pointSize() * 3 / 2); QFont font2 = font; font2.setFamily(text); bool hasLatin; QFontDatabase::WritingSystem system = writingSystemForFont(font2, &hasLatin); if (hasLatin) font = font2; QRect r = option.rect; if (option.state & QStyle::State_Selected) { painter->save(); painter->setBrush(option.palette.highlight()); painter->setPen(Qt::NoPen); painter->drawRect(option.rect); painter->setPen(QPen(option.palette.highlightedText(), 0)); } const QIcon *icon = &bitmap; if (QFontDatabase().isSmoothlyScalable(text)) { icon = &truetype; } QSize actualSize = icon->actualSize(r.size()); icon->paint(painter, r, Qt::AlignLeft|Qt::AlignVCenter); if (option.direction == Qt::RightToLeft) r.setRight(r.right() - actualSize.width() - 4); else r.setLeft(r.left() + actualSize.width() + 4); QFont old = painter->font(); painter->setFont(font); // If the ascent of the font is larger than the height of the rect, // we will clip the text, so it's better to align the tight bounding rect in this case // This is specifically for fonts where the ascent is very large compared to // the descent, like certain of the Stix family. QFontMetricsF fontMetrics(font); if (fontMetrics.ascent() > r.height()) { QRectF tbr = fontMetrics.tightBoundingRect(text); painter->drawText(r.x(), r.y() + (r.height() + tbr.height()) / 2.0, text); } else { painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeading|Qt::TextSingleLine, text); } if (writingSystem != QFontDatabase::Any) system = writingSystem; if (system != QFontDatabase::Any) { int w = painter->fontMetrics().width(text + QLatin1String(" ")); painter->setFont(font2); QString sample = QFontDatabase().writingSystemSample(system); if (option.direction == Qt::RightToLeft) r.setRight(r.right() - w); else r.setLeft(r.left() + w); painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeading|Qt::TextSingleLine, sample); } painter->setFont(old); if (option.state & QStyle::State_Selected) painter->restore(); }
void LedgerDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); // never change the background of the cell the mouse is hovering over opt.state &= ~QStyle::State_MouseOver; // show the focus only on the detail column opt.state &= ~QStyle::State_HasFocus; if(index.column() == LedgerModel::DetailColumn) { QAbstractItemView* view = qobject_cast< QAbstractItemView* >(parent()); if(view) { if(view->currentIndex().row() == index.row()) { opt.state |= QStyle::State_HasFocus; } } } painter->save(); // Background QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget); // Do not paint text if the edit widget is shown const LedgerView *view = qobject_cast<const LedgerView *>(opt.widget); if (view && view->indexWidget(index)) { painter->restore(); return; } const int margin = style->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1; const QRect textArea = QRect(opt.rect.x() + margin, opt.rect.y() + margin, opt.rect.width() - 2 * margin, opt.rect.height() - 2 * margin); QStringList lines; if(index.column() == LedgerModel::DetailColumn) { lines << index.model()->data(index, LedgerModel::PayeeNameRole).toString(); lines << index.model()->data(index, LedgerModel::CounterAccountRole).toString(); lines << index.model()->data(index, LedgerModel::SingleLineMemoRole).toString(); lines.removeAll(QString()); } const bool erroneous = index.model()->data(index, LedgerModel::ErroneousRole).toBool(); const bool selected = opt.state & QStyle::State_Selected; // draw the text items if(!opt.text.isEmpty() || !lines.isEmpty()) { // check if it is a scheduled transaction and display it as inactive if(!index.model()->data(index, LedgerModel::ScheduleIdRole).toString().isEmpty()) { opt.state &= ~QStyle::State_Enabled; } QPalette::ColorGroup cg = (opt.state & QStyle::State_Enabled) ? QPalette::Normal : QPalette::Disabled; if (cg == QPalette::Normal && !(opt.state & QStyle::State_Active)) { cg = QPalette::Inactive; } if (opt.state & QStyle::State_Selected) { painter->setPen(opt.palette.color(cg, QPalette::HighlightedText)); } else { painter->setPen(opt.palette.color(cg, QPalette::Text)); } if (opt.state & QStyle::State_Editing) { painter->setPen(opt.palette.color(cg, QPalette::Text)); painter->drawRect(textArea.adjusted(0, 0, -1, -1)); } // Don't play with the color if it's selected // otherwise switch the color if the transaction has errors if(erroneous && !selected) { painter->setPen(m_erroneousColor); } // collect data for the various colums if(index.column() == LedgerModel::DetailColumn) { for(int i = 0; i < lines.count(); ++i) { painter->drawText(textArea.adjusted(0, (opt.fontMetrics.lineSpacing() + 5) * i, 0, 0), opt.displayAlignment, lines[i]); } } else { painter->drawText(textArea, opt.displayAlignment, opt.text); } } // draw the focus rect if(opt.state & QStyle::State_HasFocus) { QStyleOptionFocusRect o; o.QStyleOption::operator=(opt); o.rect = style->proxy()->subElementRect(QStyle::SE_ItemViewItemFocusRect, &opt, opt.widget); o.state |= QStyle::State_KeyboardFocusChange; o.state |= QStyle::State_Item; QPalette::ColorGroup cg = (opt.state & QStyle::State_Enabled) ? QPalette::Normal : QPalette::Disabled; o.backgroundColor = opt.palette.color(cg, (opt.state & QStyle::State_Selected) ? QPalette::Highlight : QPalette::Window); style->proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter, opt.widget); } if((index.column() == LedgerModel::DetailColumn) && erroneous) { QPixmap attention; attention.loadFromData(attentionSign, sizeof(attentionSign), 0, 0); style->proxy()->drawItemPixmap(painter, option.rect, Qt::AlignRight | Qt::AlignTop, attention); } painter->restore(); #if 0 const QHeaderView* horizontalHeader = view->horizontalHeader(); const QHeaderView* verticalHeader = view->verticalHeader(); const QWidget* viewport = view->viewport(); const bool showGrid = view->showGrid() && !view->indexWidget(index); const int gridSize = showGrid ? 1 : 0; const int gridHint = style->styleHint(QStyle::SH_Table_GridLineColor, &option, view); const QColor gridColor = static_cast<QRgb>(gridHint); const QPen gridPen = QPen(gridColor, 0, view->gridStyle()); const bool rightToLeft = view->isRightToLeft(); const int viewportOffset = horizontalHeader->offset(); // QStyledItemDelegate::paint(painter, opt, index); if(!horizontalHeader->isSectionHidden(LedgerModel::DateColumn)) { QDate postDate = index.data(LedgerModel::PostDateRole).toDate(); if(postDate.isValid()) { int ofs = horizontalHeader->sectionViewportPosition(LedgerModel::DateColumn) + viewportOffset; QRect oRect = opt.rect; opt.displayAlignment = Qt::AlignLeft | Qt::AlignTop; opt.rect.setLeft(opt.rect.left()+ofs); opt.rect.setTop(opt.rect.top()+margin); opt.rect.setWidth(horizontalHeader->sectionSize(LedgerModel::DateColumn)); opt.text = KGlobal::locale()->formatDate(postDate, QLocale::ShortFormat); style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); opt.rect = oRect; } } if(!horizontalHeader->isSectionHidden(LedgerModel::DetailColumn)) { QString payee = index.data(LedgerModel::PayeeRole).toString(); QString counterAccount = index.data(LedgerModel::CounterAccountRole).toString(); QString txt = payee; if(payee.length() > 0) txt += '\n'; txt += counterAccount; int ofs = horizontalHeader->sectionViewportPosition(LedgerModel::DetailColumn) + viewportOffset; QRect oRect = opt.rect; opt.displayAlignment = Qt::AlignLeft | Qt::AlignTop; opt.rect.setLeft(opt.rect.left()+ofs); opt.rect.setTop(opt.rect.top()+margin); opt.rect.setWidth(horizontalHeader->sectionSize(LedgerModel::DetailColumn)); opt.text = txt; style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); opt.rect = oRect; } #if 0 opt.features |= QStyleOptionViewItemV2::HasDisplay; QString txt = QString("%1").arg(index.isValid() ? "true" : "false"); if(index.isValid()) txt += QString(" %1 - %2").arg(index.row()).arg(view->verticalHeader()->sectionViewportPosition(index.row())); opt.text = displayText(txt, opt.locale); style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); #endif // paint grid if(showGrid) { painter->save(); QPen old = painter->pen(); painter->setPen(gridPen); // qDebug() << "Paint grid for" << index.row() << "in" << opt.rect; for(int i=0; i < horizontalHeader->count(); ++i) { if(!horizontalHeader->isSectionHidden(i)) { int ofs = horizontalHeader->sectionViewportPosition(i) + viewportOffset; if(!rightToLeft) { ofs += horizontalHeader->sectionSize(i) - gridSize; } if(ofs-viewportOffset < viewport->width()) { // I have no idea, why I need to paint the grid for the selected row and the one below // but it was the only way to get this working correctly. Otherwise the grid was missing // while moving the mouse over the view from bottom to top. painter->drawLine(opt.rect.x()+ofs, opt.rect.y(), opt.rect.x()+ofs, opt.rect.height()); painter->drawLine(opt.rect.x()+ofs, opt.rect.y()+verticalHeader->sectionSize(index.row()), opt.rect.x()+ofs, opt.rect.height()); } } } painter->setPen(old); painter->restore(); } #endif }
void QmlConsoleItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV4 opt = option; initStyleOption(&opt, index); painter->save(); // Set Colors QColor textColor; QIcon taskIcon; ConsoleItem::ItemType type = (ConsoleItem::ItemType)index.data( ConsoleItem::TypeRole).toInt(); switch (type) { case ConsoleItem::DebugType: textColor = QColor(CONSOLE_LOG_TEXT_COLOR); taskIcon = m_logIcon; break; case ConsoleItem::WarningType: textColor = QColor(CONSOLE_WARNING_TEXT_COLOR); taskIcon = m_warningIcon; break; case ConsoleItem::ErrorType: textColor = QColor(CONSOLE_ERROR_TEXT_COLOR); taskIcon = m_errorIcon; break; case ConsoleItem::InputType: textColor = QColor(CONSOLE_EDITOR_TEXT_COLOR); taskIcon = m_prompt; break; default: textColor = QColor(CONSOLE_EDITOR_TEXT_COLOR); break; } // Paint background QColor backgroundColor = drawBackground(painter, opt.rect, index, bool(opt.state & QStyle::State_Selected)); // Calculate positions const QTreeView *view = qobject_cast<const QTreeView *>(opt.widget); int level = 0; QModelIndex idx(index); while (idx.parent() != QModelIndex()) { idx = idx.parent(); level++; } int width = view->width() - level * view->indentation() - view->verticalScrollBar()->width(); bool showTypeIcon = index.parent() == QModelIndex(); bool showExpandableIcon = type == ConsoleItem::DefaultType; QRect rect(opt.rect.x(), opt.rect.top(), width, opt.rect.height()); ConsoleItemPositions positions(rect, opt.font, showTypeIcon, showExpandableIcon); // Paint TaskIconArea: if (showTypeIcon) painter->drawPixmap(positions.adjustedLeft(), positions.adjustedTop(), taskIcon.pixmap(positions.typeIconWidth(), positions.typeIconHeight())); // Set Text Color painter->setPen(textColor); // Paint TextArea: // Layout the description QString str = index.data(Qt::DisplayRole).toString(); bool showFileLineInfo = true; // show complete text if selected if (view->selectionModel()->currentIndex() == index) { QTextLayout tl(str, opt.font); layoutText(tl, positions.textAreaWidth(), &showFileLineInfo); tl.draw(painter, QPoint(positions.textAreaLeft(), positions.adjustedTop())); } else { QFontMetrics fm(opt.font); painter->drawText(positions.textArea(), fm.elidedText(str, Qt::ElideRight, positions.textAreaWidth())); } // skip if area is editable if (showExpandableIcon) { // Paint ExpandableIconArea: QIcon expandCollapseIcon; if (index.model()->rowCount(index) || index.model()->canFetchMore(index)) { if (view->isExpanded(index)) expandCollapseIcon = m_collapseIcon; else expandCollapseIcon = m_expandIcon; } painter->drawPixmap(positions.expandCollapseIconLeft(), positions.adjustedTop(), expandCollapseIcon.pixmap(positions.expandCollapseIconWidth(), positions.expandCollapseIconHeight())); } if (showFileLineInfo) { // Check for file info QString file = index.data(ConsoleItem::FileRole).toString(); const QUrl fileUrl = QUrl(file); if (fileUrl.isLocalFile()) file = fileUrl.toLocalFile(); if (!file.isEmpty()) { QFontMetrics fm(option.font); // Paint FileArea const int pos = file.lastIndexOf(QLatin1Char('/')); if (pos != -1) file = file.mid(pos +1); const int realFileWidth = fm.width(file); painter->setClipRect(positions.fileArea()); painter->drawText(positions.fileAreaLeft(), positions.adjustedTop() + fm.ascent(), file); if (realFileWidth > positions.fileAreaWidth()) { // draw a gradient to mask the text int gradientStart = positions.fileAreaLeft() - 1; QLinearGradient lg(gradientStart + ELLIPSIS_GRADIENT_WIDTH, 0, gradientStart, 0); lg.setColorAt(0, Qt::transparent); lg.setColorAt(1, backgroundColor); painter->fillRect(gradientStart, positions.adjustedTop(), ELLIPSIS_GRADIENT_WIDTH, positions.lineHeight(), lg); } // Paint LineArea QString lineText = index.data(ConsoleItem::LineRole).toString(); painter->setClipRect(positions.lineArea()); const int realLineWidth = fm.width(lineText); painter->drawText(positions.lineAreaRight() - realLineWidth, positions.adjustedTop() + fm.ascent(), lineText); } } painter->setClipRect(opt.rect); painter->restore(); }
void synthv1widget_controls_item_delegate::setEditorData ( QWidget *pEditor, const QModelIndex& index ) const { #ifdef CONFIG_DEBUG_0 qDebug("synthv1widget_controls_item_delegate::setEditorData(%p, %d, %d)", pEditor, index.row(), index.column()); #endif switch (index.column()) { case 0: // Channel. { const int iChannel = index.data().toInt(); // = index.model()->data(index, Qt::DisplayRole).toInt(); QSpinBox *pSpinBox = qobject_cast<QSpinBox *> (pEditor); if (pSpinBox) pSpinBox->setValue(iChannel); break; } case 1: // Type. { const QString& sText = index.data().toString(); // = index.model()->data(index, Qt::DisplayRole).toString(); QComboBox *pComboBox = qobject_cast<QComboBox *> (pEditor); if (pComboBox) { const int iIndex = pComboBox->findText(sText); if (iIndex >= 0) pComboBox->setCurrentIndex(iIndex); else pComboBox->setCurrentIndex(0); } break; } case 2: // Parameter. { const int iParam = index.data(Qt::UserRole).toInt(); // = index.model()->data(index, Qt::DisplayRole).toString(); QComboBox *pComboBox = qobject_cast<QComboBox *> (pEditor); if (pComboBox) { const int iIndex = pComboBox->findData(iParam); if (iIndex >= 0) pComboBox->setCurrentIndex(iIndex); else pComboBox->setEditText(index.data().toString()); } break; } case 3: // Subject. { const int iIndex = index.data(Qt::UserRole).toInt(); // = index.model()->data(index, Qt::DisplayRole).toInt(); QComboBox *pComboBox = qobject_cast<QComboBox *> (pEditor); if (pComboBox) pComboBox->setCurrentIndex(iIndex); break; } default: break; } }
void QgsSvgSelectorWidget::svgSelectionChanged( const QModelIndex& idx ) { QString filePath = idx.data( Qt::UserRole ).toString(); mFileLineEdit->setText( filePath ); updateCurrentSvgPath( filePath ); }
/** * Create a dokuwiki txt file with all information about unreviewed components. */ void ComponentAtcEditorWidget::onCreateUnreviewedFileRequested() { // TODO: this code should be moved into DrugsDb::IDrugDatabase // Get all unreviewed component names with their comments and suggested ATC codes QList<Unreviewed> unrev; ComponentAtcModel *model = ddiCore()->componentAtcModel(); for(int i = 0; i < model->rowCount(); ++i) { QModelIndex isRev = model->index(i, ComponentAtcModel::IsReviewed); bool reviewed = (model->data(isRev).toString().compare("Reviewed") == 0); // Reviewed component -> skip if (reviewed) continue; // Unreviewed component QModelIndex name = model->index(i, ComponentAtcModel::Name); if (name.data().toString().simplified().isEmpty()) continue; QModelIndex atc = model->index(i, ComponentAtcModel::AtcCodeList); QModelIndex sugg = model->index(i, ComponentAtcModel::SuggestedAtcCodeList); QModelIndex comment = model->index(i, ComponentAtcModel::Comments); QStringList codes; codes << sugg.data().toString().split(";", QString::SkipEmptyParts); codes << atc.data().toString().split(";", QString::SkipEmptyParts); codes.removeDuplicates(); codes.removeAll(""); unrev << Unreviewed(name.data().toString(), codes, comment.data().toString()); // TODO: How to add all drug brandname containing the component (using DrugsDb but we are in DDI) } qSort(unrev.begin(), unrev.end(), Unreviewed::lessThan); // Create a wiki like file content QString toc; toc += QString("====== Unreviewed components: %1 ======\n\n\n" " * Number of components: %2\n" " * Number of unreviewed components: %3\n" " * Date of report generation : %4" "\n\n" "%5" "\n\n" "===== Table of contents =====\n" "\n\n") .arg(model->databaseUids().join("; ")) .arg(model->rowCount()) .arg(unrev.count()) .arg(QLocale().toString(QDateTime::currentDateTime(), QLocale::LongFormat)) .arg(WIKI_NOTE); QMap<QChar, QString> wikis; QChar current; int nbCurrent = 0; QString wiki; foreach(const Unreviewed &ur, unrev) { QString normalizedName = Utils::removeAccents(ur.name); if (current.isNull()) if (!normalizedName[0].isLetter()) current = '0'; else current = normalizedName[0]; else if (current != normalizedName[0]) { // All numbers and [ ( stay in the same block if (normalizedName[0].isLetter()) { // New char -> Store the current wiki content createNewWikiContent(model->databaseUids(), wikis, wiki, current, nbCurrent); current = normalizedName[0]; } } ++nbCurrent; // Create ATC links QString atc; foreach(const QString &code, ur.suggested) atc += QString("\n * [[http://www.whocc.no/atc_ddd_index/?code=%1|%1]]").arg(code); // Create component search links // TODO: improve this for non-french drug database (we don't need CNAMTS links) // TODO: add link: http://www.kegg.jp/kegg-bin/search?q=COMPONENT_NAME&display=drug&from=drug QString search; search += QString("\n * [[%1|Search CNAMTS database]]").arg(QString("http://www.codage.ext.cnamts.fr/codif/bdm//critere/index_lis_rech.php?p_nom_rech=%1%2&p_remb=tout&p_cri=subact&p_site=").arg("%25").arg(Utils::removeAccents(ur.name.toUpper()).simplified())); search += QString("\n * [[%1|Search Google]]").arg(QString("http://www.google.fr/search?rls=en&q=%1+atc&ie=UTF-8&oe=UTF-8&redir_esc=").arg(ur.name.toUpper())); search += QString("\n * [[%1|Search WHO ATC index]]").arg(QString("http://www.whocc.no/atc_ddd_index/?name=%1").arg(Utils::removeAccents(ur.name.toUpper()))); search += QString("\n * [[%1|Search RESIP]]").arg(QString("http://www.portailmedicaments.resip.fr/bcb_recherche/classes.asp?cc=1")); search += QString("\n * [[%1|Search WikiPedia (En)]]").arg(QString("http://en.wikipedia.org/wiki/%1").arg(Utils::firstLetterUpperCase(Utils::removeAccents(ur.name.toLower())))); search += QString("\n * [[%1|Search vidal.fr]]").arg(QString("http://www.vidal.fr/recherche/index/q:%1/").arg(Utils::removeAccents(ur.name.toLower()))); wiki += QString("===== %1 =====\n\n" " * Your proposal: \n" " * Suggested ATC codes: %2\n" " * Comment: %3\n" " * Suggested search links: %4\n" "\n\n") .arg(ur.name) .arg(atc) .arg(ur.comment) .arg(search) ; }