void QSystemTrayIconSys::createIcon()
{
    hIcon = 0;
    QIcon icon = q->icon();
    if (icon.isNull())
        return;

    const int iconSizeX = GetSystemMetrics(SM_CXSMICON);
    const int iconSizeY = GetSystemMetrics(SM_CYSMICON);
    QSize size = icon.actualSize(QSize(iconSizeX, iconSizeY));
    QPixmap pm = icon.pixmap(size);
    if (pm.isNull())
        return;

    hIcon = pm.toWinHICON();
}
Exemple #2
0
QStyleOptionTitleBar Q3TitleBarPrivate::getStyleOption() const
{
    Q_Q(const Q3TitleBar);
    QStyleOptionTitleBar opt;
    opt.init(q);
    opt.text = q->windowTitle();
    //################
    QIcon icon = q->windowIcon();
    QSize s = icon.actualSize(QSize(64, 64));
    opt.icon = icon.pixmap(s);
    opt.subControls = QStyle::SC_All;
    opt.activeSubControls = QStyle::SC_None;
    opt.titleBarState = titleBarState();
    opt.titleBarFlags = flags;
    return opt;
}
void FriendItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QStyledItemDelegate::paint(painter, option, index);

    painter->save();

    QSize hint = sizeHint(option, index);

    //Status Icon
    QIcon statusIcon = QIcon(StatusHelper::getInfo(getStatus(index)).iconPath);
    QSize statusIconSize = statusIcon.actualSize(option.decorationSize);

    static const int ICON_X_OFFSET = 0;

    painter->drawPixmap(ICON_X_OFFSET, option.rect.top() + (hint.height() - statusIconSize.height())/2, statusIcon.pixmap(statusIconSize.width(), statusIconSize.height()));


    //Username
    QString username = index.data(UsernameRole).toString();

    QString statusMessage = index.data(StatusMessageRole).toString();
    const bool statusMessageIsVisible = statusMessage.trimmed().length() != 0;

    QFont usernameFont = QApplication::font();

    static const int USERNAME_X_OFFSET = 2;
    static const int USERNAME_Y_OFFSET = -3;

    painter->setFont(usernameFont);
    QString elidedUsername = painter->fontMetrics().elidedText(username, Qt::ElideRight, option.rect.right() - (ICON_X_OFFSET + statusIconSize.width() + USERNAME_X_OFFSET));
    painter->drawText(ICON_X_OFFSET + statusIconSize.width() + USERNAME_X_OFFSET, option.rect.top() + hint.height()/2 + ((statusMessageIsVisible ? 0 : painter->fontMetrics().ascent()) - painter->fontMetrics().descent())/2 + (statusMessageIsVisible ? USERNAME_Y_OFFSET : 0), elidedUsername);

    if (statusMessageIsVisible) {
        //Status Message
        QFont statusMessageFont = QApplication::font();

        painter->setPen(Qt::gray);

        static const int STATUSMESSAGE_X_OFFSET = USERNAME_X_OFFSET;

        painter->setFont(statusMessageFont);
        QString elidedStatuseMessage = painter->fontMetrics().elidedText(statusMessage, Qt::ElideRight, option.rect.right() - (ICON_X_OFFSET + statusIconSize.width() + STATUSMESSAGE_X_OFFSET));
        painter->drawText(ICON_X_OFFSET + statusIconSize.width() + STATUSMESSAGE_X_OFFSET, option.rect.top() + hint.height()/2 + painter->fontMetrics().ascent(), elidedStatuseMessage);
    }

    painter->restore();
}
void ListItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QListWidget *eventlist = (QListWidget*) this->parent();
    bool isFocusedList = true;
    if (eventlist)
        isFocusedList = eventlist->hasFocus();

    bool isSelectedItem = option.state & QStyle::State_Selected;
    QString text = index.data(Qt::DisplayRole).toString();
    text = getHtmlWithColours(text, isSelectedItem, isFocusedList);
    QIcon icon = index.data(Qt::DecorationRole).value<QIcon>();
    QSize iconSize = icon.actualSize(QSize(option.rect.size().height() * 2, option.rect.size().height()));
    QRect iconRect = QRect(option.rect.x() + EVENT_ITEM_ICON_MARGIN, option.rect.y() + EVENT_ITEM_ICON_MARGIN, iconSize.width(), iconSize.height());
    QPixmap iconPixmap = icon.pixmap(iconSize);
    QPoint textTopLeft = QPoint(iconRect.x() + iconSize.width() + EVENT_ITEM_ICON_MARGIN + EVENT_ITEM_TEXT_MARGIN, option.rect.y() + EVENT_ITEM_ICON_MARGIN + EVENT_ITEM_TEXT_MARGIN);
    QSize textSize = QSize(option.rect.width() - textTopLeft.x(), option.rect.height() - textTopLeft.y());
    QRect textRect = QRect(textTopLeft, textSize);
    QTextDocument document;
    document.setUndoRedoEnabled(false);

    if (isSelectedItem)
    {
        const QPalette::ColorRole color = (isFocusedList) ? QPalette::Highlight : QPalette::Window;
        painter->resetTransform();
        painter->fillRect(option.rect, option.palette.color(color));
    }

    //painter->save();
    //painter->restore();
    painter->resetTransform();

    document.setHtml(text);
    painter->drawPixmap(iconRect, iconPixmap);

    //painter->save();
    //painter->restore();
    painter->resetTransform();
    painter->translate(textRect.topLeft());
    painter->setRenderHint(QPainter::Antialiasing, true);

    document.drawContents(painter);

    //painter->save();
    //painter->restore();
}
void HtmlDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    if (!index.isValid())
        return;

    QStyleOptionViewItemV4 options = option;
    initStyleOption(&options, index);

    painter->save();

    QTextDocument doc;
    doc.setHtml(options.text);
    QIcon icon = options.icon;

    options.text = "";
    options.icon = QIcon();
    options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter);

    // Draw icon ................................
    QSize iconSize = icon.actualSize(mIconSize);
    painter->translate(options.rect.left(), options.rect.top());
    QRect iconRect = QRect(4, 4, iconSize.width(), iconSize.height());

    icon.paint(painter, iconRect);

    doc.setTextWidth(options.rect.width() - iconRect.right() - 10);

    // shift text right to make icon visible
    painter->translate(iconRect.right() + 8, 0);
    QRect clip(0, 0, options.rect.width()-iconRect.right()- 10, options.rect.height());


    painter->setClipRect(clip);
    QAbstractTextDocumentLayout::PaintContext ctx;
    // set text color to red for selected item
    if (option.state & QStyle::State_Selected)
    {
        ctx.palette.setColor(QPalette::Text, option.palette.color(QPalette::HighlightedText));
    }
    ctx.clip = clip;
    doc.documentLayout()->draw(painter, ctx);

    painter->restore();
}
Exemple #6
0
void QUrlModel::setUrl(const QModelIndex &index, const QUrl &url, const QModelIndex &dirIndex)
{
    setData(index, url, UrlRole);
    if (url.path().isEmpty()) {
        setData(index, fileSystemModel->myComputer());
        setData(index, fileSystemModel->myComputer(Qt::DecorationRole), Qt::DecorationRole);
    } else {
        QString newName;
        if (showFullPath) {
            //On windows the popup display the "C:\", convert to nativeSeparators
            newName = QDir::toNativeSeparators(dirIndex.data(QFileSystemModel::FilePathRole).toString());
        } else {
            newName = dirIndex.data().toString();
        }

        QIcon newIcon = qvariant_cast<QIcon>(dirIndex.data(Qt::DecorationRole));
        if (!dirIndex.isValid()) {
            const QFileIconProvider *provider = fileSystemModel->iconProvider();
            if (provider)
                newIcon = provider->icon(QFileIconProvider::Folder);
            newName = QFileInfo(url.toLocalFile()).fileName();
            if (!invalidUrls.contains(url))
                invalidUrls.append(url);
            //The bookmark is invalid then we set to false the EnabledRole
            setData(index, false, EnabledRole);
        } else {
            //The bookmark is valid then we set to true the EnabledRole
            setData(index, true, EnabledRole);
        }

        // Make sure that we have at least 32x32 images
        const QSize size = newIcon.actualSize(QSize(32,32));
        if (size.width() < 32) {
            QPixmap smallPixmap = newIcon.pixmap(QSize(32, 32));
            newIcon.addPixmap(smallPixmap.scaledToWidth(32, Qt::SmoothTransformation));
        }

        if (index.data().toString() != newName)
            setData(index, newName);
        QIcon oldIcon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        if (oldIcon.cacheKey() != newIcon.cacheKey())
            setData(index, newIcon, Qt::DecorationRole);
    }
}
QSize QtopiaCLItemDelegate::variantSize(QPaintDevice *device,
                                        const QStyleOptionViewItem &option, 
                                        const QVariant &value) const
{
  QSize maxsize(65535,65535);
  if (!value.isNull())
  {
    switch (value.type())
    {
    case QVariant::Invalid:
      break;
    case QVariant::Pixmap:
      return qvariant_cast<QPixmap>(value).size();
    case QVariant::Image:
      return qvariant_cast<QImage>(value).size();
    case QVariant::Icon:
    {
      QIcon icon = qvariant_cast<QIcon>(value);
      return icon.actualSize(maxsize);
    }
    case QVariant::List:
    {
      int maxh=0;
      int width=0;
      foreach(const QVariant &item, value.toList())
      {
        QSize item_size = variantSize(device, option, item);
        width += item_size.width();
        maxh = qMax(maxh, item_size.height());
      }
      return QSize(width,maxh);
    }
    case QVariant::String:
    {
      QFontMetrics fm(option.font, device);
      return QSize(fm.width(value.toString()), fm.height());
    }
    default:
      break;
    }
  }
  return QSize(0,0);
}
int KateCompletionTree::columnTextViewportPosition(int column) const
{
    int ret = columnViewportPosition(column);
    QModelIndex i = model()->index(0, column, QModelIndex());
    QModelIndex base = model()->index(0, 0, QModelIndex());

    //If it's just a group header, use the first child
    if (base.isValid() && model()->rowCount(base)) {
        i = base.child(0, column);
    }

    if (i.isValid()) {
        QIcon icon = i.data(Qt::DecorationRole).value<QIcon>();
        if (!icon.isNull()) {
            ret += icon.actualSize(sizeHintForIndex(i)).width();
        }
    }
    return ret;
}
bool IconTranslationMatrix::fromTheme(QString name, bool is_active,
                                     QPixmap *pixmap) {
  QIcon icon = QIcon::fromTheme(name, QIcon());
  if (icon.isNull()) {
    return false;
  }

  // Draw the icon on the pixmap. The actual icon size is probably smaller than
  // the size we need, so we need to center it.
  QPainter painter(pixmap);
  QIcon::Mode mode = (is_active) ? QIcon::Normal : QIcon::Disabled;
  QSize actual = icon.actualSize(pixmap->size(), mode);
  QSize req    = pixmap->size();
  painter.drawPixmap(req.width()  / 2 - actual.width()  / 2,
                     req.height() / 2 - actual.height() / 2,
                     icon.pixmap(req, mode));
  painter.end();

  return true;
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void PdmUiLineEditor::configureAndUpdateUi(const QString& uiConfigName)
{
    assert(!m_lineEdit.isNull());
    assert(!m_label.isNull());

    QIcon ic = field()->uiIcon(uiConfigName);
    if (!ic.isNull())
    {
        m_label->setPixmap(ic.pixmap(ic.actualSize(QSize(64, 64))));
    }
    else
    {
        m_label->setText(field()->uiName(uiConfigName));
    }

    m_label->setEnabled(!field()->isUiReadOnly(uiConfigName));
    m_label->setToolTip(field()->uiToolTip(uiConfigName));

    m_lineEdit->setEnabled(!field()->isUiReadOnly(uiConfigName));
    m_lineEdit->setToolTip(field()->uiToolTip(uiConfigName));

    PdmUiLineEditorAttribute leab;
    field()->ownerObject()->editorAttribute(field(), uiConfigName, &leab);
    if (leab.useRangeValidator)
    {
        m_lineEdit->setValidator(new QIntValidator(leab.minValue, leab.maxValue, this));
    }

    bool fromMenuOnly = false;
    QList<PdmOptionItemInfo> enumNames = field()->valueOptions(&fromMenuOnly);
    if (!enumNames.isEmpty() && fromMenuOnly == true)
    {
        QStringList uiTexts = PdmOptionItemInfo::extractUiTexts(enumNames);
        int enumValue = field()->uiValue().toInt();
        m_lineEdit->setText(uiTexts.at(enumValue));
    }
    else
    {
        m_lineEdit->setText(field()->uiValue().toString());
    }
}
void ListviewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                           const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter,option,index);

    painter->save();

    QFontMetrics fm(font);

    QIcon icon = qvariant_cast<QIcon>(index.data(IconRole));
    QString headerText = qvariant_cast<QString>(index.data(headerTextRole));
    QString subText = qvariant_cast<QString>(index.data(subHeaderTextrole));

    QSize iconsize = icon.actualSize(option.decorationSize);

    QRect headerRect = option.rect;
    QRect subheaderRect = option.rect;
    QRect iconRect = subheaderRect;

    iconRect.setRight(iconsize.width()+30);
    iconRect.setTop(iconRect.top());
    headerRect.setLeft(30);
    subheaderRect.setLeft(30);
    headerRect.setTop(headerRect.top()+1);
    headerRect.setBottom(headerRect.top()+fm.height());

    subheaderRect.setTop(headerRect.bottom()-5);

    painter->drawPixmap(QPoint(iconRect.left()+iconsize.width()/2,iconRect.top()+iconsize.height()/2),icon.pixmap(iconsize.width(),iconsize.height()));

    painter->setFont(font);
    painter->drawText(headerRect,headerText);


    painter->setFont(SubFont);
    painter->drawText(subheaderRect.left(),subheaderRect.top()+17,subText);

    painter->restore();

}
QVariant AddAccountDialogWrapper::data(const QModelIndex &index, int role) const
{
	if (index.row() < 0 || index.row() > m_wizards->size())
		return QVariant();
	AccountCreationWizard *wizard = m_wizards->at(index.row());
	ExtensionInfo info = wizard->info();
	QIcon icon = info.icon();
	if (!icon.actualSize(QSize(1,1)).isValid())
		icon = Icon("applications-internet");
	switch (role) {
	case Qt::DisplayRole:
		return info.name().toString();
	case Qt::DecorationRole:
		return QString();
	case WizardRole:
		return m_wizards->indexOf(wizard);
	case InfoRole:{
		return info.description().toString();}
	default:
		return QVariant();
	}

}
void RefactorOverlay::paintMarker(const RefactorMarker& marker, QPainter *painter, const QRect &clip)
{
    QPointF offset = m_editor->contentOffset();
    QRectF geometry = m_editor->blockBoundingGeometry(marker.cursor.block()).translated(offset);

    if (geometry.top() > clip.bottom() + 10 || geometry.bottom() < clip.top() - 10)
        return; // marker not visible

    QTextCursor cursor = marker.cursor;

    QRect r = m_editor->cursorRect(cursor);

    QIcon icon = marker.icon;
    if (icon.isNull())
        icon = m_icon;

    QSize sz = icon.actualSize(QSize(m_editor->fontMetrics().width(QLatin1Char(' '))+2, r.height()));

    int x = r.right();
    marker.rect = QRect(x, r.top(), sz.width(), sz.height());

    icon.paint(painter, marker.rect);
    m_maxWidth = qMax((qreal)m_maxWidth, x + sz.width() - offset.x());
}
Exemple #14
0
	void M11TabBar::paintEvent(QPaintEvent*)
	{
		QStyleOptionTab tabOverlap;
		tabOverlap.shape = shape();
		int overlap = style()->pixelMetric(QStyle::PM_TabBarBaseOverlap, &tabOverlap, this);
		QWidget *theParent = parentWidget();
		QStyleOptionTabBarBase optTabBase;
		optTabBase.init(this);
		optTabBase.shape = shape();
		if (theParent && overlap > 0) {
			QRect rect;
			switch (tabOverlap.shape) {
			case M11TabBar::RoundedNorth:
			case M11TabBar::TriangularNorth:
				rect.setRect(0, height() - overlap, width(), overlap);
				break;
			case M11TabBar::RoundedSouth:
			case M11TabBar::TriangularSouth:
				rect.setRect(0, 0, width(), overlap);
				break;
			case M11TabBar::RoundedEast:
			case M11TabBar::TriangularEast:
				rect.setRect(0, 0, overlap, height());
				break;
			case M11TabBar::RoundedWest:
			case M11TabBar::TriangularWest:
				rect.setRect(width() - overlap, 0, overlap, height());
				break;
			}
			optTabBase.rect = rect;
		}

		QStylePainter p(this);
		p.fillRect(rect(), Utils::instance().gradientTopToBottom(rect()));
		QPen pen = p.pen();

		int selected = -1;
		int cut = -1;
		bool rtl = optTabBase.direction == Qt::RightToLeft;
		bool verticalTabs = (shape() == M11TabBar::RoundedWest || shape() == M11TabBar::RoundedEast
		                     || shape() == M11TabBar::TriangularWest
		                     || shape() == M11TabBar::TriangularEast);
		QStyleOptionTab cutTab;
		QStyleOptionTab selectedTab;
		for (int i = 0; i < count(); ++i) {
			QStyleOptionTabV2 tab = getStyleOption(i);
			if (!(tab.state & QStyle::State_Enabled)) {
				tab.palette.setCurrentColorGroup(QPalette::Disabled);
			}
			// If this tab is partially obscured, make a note of it so that we can pass the information
			// along when we draw the tear.
			if ((!verticalTabs && (!rtl && tab.rect.left() < 0) ||
			     (rtl && tab.rect.right() > width())) ||
			    (verticalTabs && tab.rect.top() < 0)) {
				cut = i;
				cutTab = tab;
			}
			// Don't bother drawing a tab if the entire tab is outside of the visible tab bar.
			if ((!verticalTabs && (tab.rect.right() < 0 || tab.rect.left() > width()))
			    || (verticalTabs && (tab.rect.bottom() < 0 || tab.rect.top() > height())))
				continue;

			optTabBase.tabBarRect |= tab.rect;
			if (i == currentIndex()) {
				selected = i;
				selectedTab = tab;
				optTabBase.selectedTabRect = tab.rect;
			}

			QIcon icon = tabIcon(i);
			QSize iconSize = icon.actualSize(QSize(tab.rect.height(), tab.rect.height()));
			int iconMargin = (tab.rect.height() - iconSize.height()) / 2;
			QRect iconRect(tab.rect.left() + iconMargin, tab.rect.top(), iconSize.width(), tab.rect.height());
			QString text = tabText(i);
			QRect textRect(
			    tab.rect.left() + iconMargin + iconSize.width(),
			    tab.rect.top(),
			    tab.rect.width() - iconSize.width(),
			    tab.rect.height()
			);

			p.fillRect(
			    tab.rect,
			    i == currentIndex() ?
			    Utils::instance().palette().base() :
			    tab.rect.contains(mapFromGlobal(QCursor::pos())) ?
			    Utils::instance().palette().light() : Utils::instance().gradientTopToBottom(tab.rect)
			);

			p.setPen(Utils::instance().palette().dark().color());

			switch (shape()) { // override the widget's border to make it consistent over inactive tabs
			case M11TabBar::RoundedNorth:
			case M11TabBar::TriangularNorth:
				if (i == currentIndex()) {
					p.drawRect(tab.rect.adjusted(0, 0, -1, 0));
				}
				else {
					p.drawLine(tab.rect.bottomLeft(), tab.rect.bottomRight());
				}
				break;
			case M11TabBar::RoundedSouth:
			case M11TabBar::TriangularSouth:
				if (i == currentIndex()) {
					p.drawRect(tab.rect.adjusted(0, -1, -1, -1));
				}
				else {
					p.drawLine(tab.rect.topLeft(), tab.rect.topRight());
				}
				break;
			case M11TabBar::RoundedEast:
			case M11TabBar::TriangularEast:
				if (i == currentIndex()) {
					p.drawRect(tab.rect.adjusted(-1, 0, -1, -1));
				}
				else {
					p.drawLine(tab.rect.topLeft(), tab.rect.bottomLeft());
				}
				break;
			case M11TabBar::RoundedWest:
			case M11TabBar::TriangularWest:
				if (i == currentIndex()) {
					p.drawRect(tab.rect.adjusted(0, 0, 0, -1));
				}
				else {
					p.drawLine(tab.rect.topRight(), tab.rect.bottomRight());
				}
				break;
			default:
				Q_ASSERT(false);
				break;
			}

			p.setPen(m_tabLabelColors.contains(i) ? m_tabLabelColors.value(i).color() : pen);

			QString textToDraw = fontMetrics().elidedText(
			                         text,
			                         elideMode(),
			                         1 + (
			                             verticalTabs ? tabRect(i).height() : tabRect(i).width()
			                         ) - style()->pixelMetric(QStyle::PM_TabBarTabHSpace, &tab, this),
			                         Qt::TextShowMnemonic
			                     );

			p.drawItemPixmap(iconRect, Qt::AlignCenter, icon.pixmap(iconSize));

			p.drawItemText(
			    textRect,
			    Qt::AlignLeft | Qt::AlignVCenter,
			    QPalette(),
			    tab.state & QStyle::State_Enabled,
			    textToDraw
			);

			p.setPen(pen);
		}

		if (!drawBase()) {
			p.setBackgroundMode(Qt::TransparentMode);
		}
		else {
			// p.drawPrimitive(QStyle::PE_FrameTabBarBase, optTabBase);
		}

		// Only draw the tear indicator if necessary. Most of the time we don't need too.
		if (cut >= 0) {
			cutTab.rect = rect();
			cutTab.rect = style()->subElementRect(QStyle::SE_TabBarTearIndicator, &cutTab, this);
			p.drawPrimitive(QStyle::PE_IndicatorTabTear, cutTab);
		}

		// p.setPen(Qt::black);
		// p.drawRect(rect());
	}
void KonqComboItemDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option,
                                   const QModelIndex &index ) const
{
    QIcon icon = qvariant_cast<QIcon>( index.data( Qt::DecorationRole ) );
    QString url = index.data( Qt::DisplayRole ).toString();
    QString title = index.data( Qt::UserRole ).toString();

    QIcon::Mode mode = option.state & QStyle::State_Enabled ? QIcon::Normal : QIcon::Disabled;
    const QSize size = icon.actualSize( option.decorationSize, mode );
    QPixmap pixmap = icon.pixmap( size, mode );

    QStyleOptionViewItemV3 opt( option );

    painter->save();

    // Draw the item background

    // ### When Qt 4.4 is released we need to change this code to draw the background
    //     by calling QStyle::drawPrimitive() with PE_PanelItemViewRow.
    if ( opt.state & QStyle::State_Selected ) {
        painter->fillRect( option.rect, option.palette.brush( QPalette::Highlight ) );
        painter->setPen( QPen( option.palette.brush( QPalette::HighlightedText ), 0 ) );
    }

    int hMargin = QApplication::style()->pixelMetric( QStyle::PM_FocusFrameHMargin );
    int vMargin = QApplication::style()->pixelMetric( QStyle::PM_FocusFrameVMargin );

    const QRect bounding = option.rect.adjusted( hMargin, vMargin, -hMargin, -vMargin );
    const QSize textSize( bounding.width() - pixmap.width() - 2, bounding.height() );
    const QRect pixmapRect = QStyle::alignedRect( option.direction, Qt::AlignLeft | Qt::AlignVCenter,
                                                  pixmap.size(), bounding );
    const QRect textRect = QStyle::alignedRect( option.direction, Qt::AlignRight, textSize, bounding );

    if ( !pixmap.isNull() )
        painter->drawPixmap( pixmapRect.topLeft(), pixmap );

    QSize titleSize( ( bounding.width() / 3 ) - 1, textRect.height() );
    if (title.isEmpty()) {
        // Don't truncate the urls when there is no title to show (e.g. local files)
        // Ideally we would do this globally for all items - reserve space for a title for all, or for none
        titleSize = QSize();
    }
    const QSize urlSize( textRect.width() - titleSize.width() - 2, textRect.height() );
    const QRect titleRect = QStyle::alignedRect( option.direction, Qt::AlignRight, titleSize, textRect );
    const QRect urlRect   = QStyle::alignedRect( option.direction, Qt::AlignLeft, urlSize, textRect );

    if ( !url.isEmpty() ) {
        QString squeezedText = option.fontMetrics.elidedText( url, Qt::ElideMiddle, urlRect.width() );
        painter->drawText( urlRect, Qt::AlignLeft | Qt::AlignVCenter, squeezedText );
    }

    if ( !title.isEmpty() ) {
        QString squeezedText = option.fontMetrics.elidedText( title, Qt::ElideRight, titleRect.width() );
        QFont font = painter->font();
        font.setItalic( true );
        painter->setFont( font );
        QColor color = painter->pen().color();
        color.setAlphaF(.75);
        painter->setPen(color);
        painter->drawText( titleRect, Qt::AlignLeft | Qt::AlignVCenter, squeezedText );
    }

    painter->restore();
}
void RssListItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter,option,index);

    painter->save();

    QFont font = QApplication::font();
    QFont SubFont = QApplication::font();
    QFont dateFont = QApplication::font();

    //font.setPixelSize(font.weight()+);
    font.setBold(true);
    SubFont.setWeight(SubFont.weight()-2);
    QFontMetrics fm(font);
    QFontMetrics dfm(dateFont);

    QIcon icon = qvariant_cast<QIcon>(index.data(IconRole));
    QString headerText = qvariant_cast<QString>(index.data(HeaderTextRole));
    QString subText = qvariant_cast<QString>(index.data(DescriptionRole));
    QString dateText = qvariant_cast<QString>(index.data(DateRole));

    QSize iconsize = icon.actualSize(option.decorationSize);

    QRect headerRect = option.rect;
    QRect subheaderRect = option.rect;
    QRect iconRect = subheaderRect;
    QRect dateRect = subheaderRect;

    iconRect.setRight(iconsize.width()+30);
    iconRect.setTop(iconRect.top()+5);
    headerRect.setLeft(iconRect.right());
    headerRect.setTop(headerRect.top()+5);
    headerRect.setBottom(headerRect.top()+fm.height());

    int dateWidth = 0;
    if(!dateText.isEmpty()) {
        dateWidth = dfm.width(dateText) + 5;
        dateRect.setLeft(iconRect.right());
        dateRect.setTop(headerRect.bottom()+17);
    }


    subheaderRect.setLeft(iconRect.right() + dateWidth);
    subheaderRect.setTop(headerRect.bottom()+17);


    //painter->drawPixmap(QPoint(iconRect.right()/2,iconRect.top()/2),icon.pixmap(iconsize.width(),iconsize.height()));
    painter->drawPixmap(QPoint(iconRect.left()+iconsize.width()/2+2,iconRect.top()+iconsize.height()/2+3),icon.pixmap(iconsize.width(),iconsize.height()));

    painter->setFont(font);
    painter->drawText(headerRect,headerText);


    painter->setFont(SubFont);
    painter->drawText(subheaderRect.left(),subheaderRect.top(),subText);

    if(dateWidth) {
        painter->setFont(dateFont);
        painter->drawText(dateRect.left(), dateRect.top(), dateText);
    }

    painter->restore();

}
Exemple #17
0
bool KrTreeWidget::event(QEvent * event)
{
    switch (event->type()) {
        // HACK: QT 4 Context menu key isn't handled properly
    case QEvent::ContextMenu: {
        QContextMenuEvent* ce = (QContextMenuEvent*) event;

        if (ce->reason() == QContextMenuEvent::Mouse) {
            QPoint pos = viewport()->mapFromGlobal(ce->globalPos());

            QTreeWidgetItem * item = itemAt(pos);
            int column = columnAt(pos.x());

            emit itemRightClicked(item, ce->globalPos(), column);
            return true;
        } else {
            if (currentItem()) {
                QRect r = visualItemRect(currentItem());
                QPoint p = viewport()->mapToGlobal(QPoint(r.x() + 5, r.y() + 5));

                emit itemRightClicked(currentItem(), p, currentColumn());
                return true;
            }
        }
    }
    break;
    case QEvent::KeyPress: {
        // HACK: QT 4 Ctrl+A bug fix: Ctrl+A doesn't work if QTreeWidget contains parent / child items
        //       Insert doesn't change the selections for multi selection modes
        QKeyEvent* ke = (QKeyEvent*) event;
        switch (ke->key()) {
        case Qt::Key_Insert: {
            if (ke->modifiers() != 0)
                break;

            QAbstractItemView::SelectionMode mode = selectionMode();

            if (mode != QAbstractItemView::ContiguousSelection && mode != QAbstractItemView::ExtendedSelection &&
                    mode != QAbstractItemView::MultiSelection)
                break;

            ke->accept();

            if (currentItem() == 0)
                return true;

            currentItem()->setSelected(!currentItem()->isSelected());
            return true;
        }
        case Qt::Key_A:
            if (ke->modifiers() == Qt::ControlModifier) {
                QAbstractItemView::SelectionMode mode = selectionMode();

                if (mode == QAbstractItemView::ContiguousSelection || mode == QAbstractItemView::ExtendedSelection ||
                        mode == QAbstractItemView::MultiSelection) {
                    selectAll();
                    ke->accept();
                    return true;
                }
            }
            break;
        default:
            break;
        }
    }
    break;
    case QEvent::Resize: {
        QResizeEvent * re = (QResizeEvent *)event;
        if (!_inResize && re->oldSize() != re->size()) {
            if (_stretchingColumn != -1 && columnCount()) {
                QList< int > columnsSizes;
                int oldSize = 0;

                for (int i = 0; i != header()->count(); i++) {
                    columnsSizes.append(header()->sectionSize(i));
                    oldSize += header()->sectionSize(i);
                }

                bool res = QTreeWidget::event(event);

                int newSize = viewport()->width();
                int delta = newSize - oldSize;

                if (delta) {
                    _inResize = true;

                    for (int i = 0; i != header()->count(); i++) {
                        if (i == _stretchingColumn) {
                            int newNs = columnsSizes[ i ] + delta;
                            if (newNs < 8)
                                newNs = 8;
                            header()->resizeSection(i, newNs);
                        } else if (header()->sectionSize(i) != columnsSizes[ i ]) {
                            header()->resizeSection(i, columnsSizes[ i ]);
                        }
                    }
                    _inResize = false;
                }
                return res;
            }
        }
        break;
    }
    case QEvent::ToolTip: {
        QHelpEvent *he = static_cast<QHelpEvent*>(event);

        if (viewport()) {
            QPoint pos = viewport()->mapFromGlobal(he->globalPos());

            QTreeWidgetItem * item = itemAt(pos);

            int column = columnAt(pos.x());

            if (item) {
                if (!item->toolTip(column).isEmpty())
                    break;

                QString tip = item->text(column);

                int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
                int requiredWidth = QFontMetrics(font()).width(tip) + 2 * textMargin;

                if (column == 0 && indentation()) {
                    int level = 0;

                    QTreeWidgetItem *parent = item;

                    while ((parent = parent->parent()))
                        level++;

                    if (rootIsDecorated())
                        level++;

                    requiredWidth += level * indentation();
                }

                QIcon icon = item->icon(column);
                if (!icon.isNull()) {
                    QStyleOptionViewItem opts = viewOptions();
                    QSize iconSize = icon.actualSize(opts.decorationSize);
                    requiredWidth += iconSize.width();

                    int pixmapMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, this) + 1;
                    requiredWidth += 2 * pixmapMargin;
                }

                if (!tip.isEmpty() && (columnWidth(column) < requiredWidth))
                    QToolTip::showText(he->globalPos(), tip, this);
                return true;
            }
        }
    }
    break;
    default:
        break;
    }
    return QTreeWidget::event(event);
}
Exemple #18
0
	QList<LicenseInfo> thirdPartyLicenses = License::thirdPartyLicenses();
	foreach(LicenseInfo li, thirdPartyLicenses) {
		qtb3rdPartyLicense->append(QString::fromLatin1("<h3>%1 (<a href=\"%2\">%2</a>)</h3><pre>%3</pre>")
				.arg(Qt::escape(li.name))
				.arg(Qt::escape(li.url))
				.arg(Qt::escape(li.license)));
	}

	qtb3rdPartyLicense->moveCursor(QTextCursor::Start);

	QWidget *about = new QWidget(qtwTab);

	QLabel *icon = new QLabel(about);
	QIcon windowIcon = QApplication::windowIcon();
	icon->setPixmap(windowIcon.pixmap(windowIcon.actualSize(QSize(128, 128))));

	QLabel *text = new QLabel(about);
	text->setOpenExternalLinks(true);
	text->setText(tr(
		"<h3>Murmur (%1)</h3>"
		"<p>%3</p>"
		"<p><tt><a href=\"%2\">%2</a></tt></p>"
	).arg(QLatin1String(MUMBLE_RELEASE))
	 .arg(QLatin1String("http://www.mumble.info/"))
	 .arg(QLatin1String("Copyright 2005-2017 The Mumble Developers")));
	QHBoxLayout *qhbl = new QHBoxLayout(about);
	qhbl->addWidget(icon);
	qhbl->addWidget(text);

	qtwTab->addTab(about, tr("&About Murmur"));
/* -----------------------------------------------------------------\
|  Method: paint
|  Begin:  22.03.2011 / 12:20
|  Author: Jo2003
|  Description: paint custom view item
|
|  Parameters: painter, view item, model index
|
|  Returns: --
\----------------------------------------------------------------- */
void QChanListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
   // paint any selection / hover effect ...
   QStyledItemDelegate::paint(painter, option, index);
   painter->save();

   /////////////////////////////////////////////////////////////////////////////
   int     iPos     = qvariant_cast<int>(index.data(channellist::posRole));
   int     iCid     = qvariant_cast<int>(index.data(channellist::cidRole));
   uint    uiStart  = qvariant_cast<uint>(index.data(channellist::startRole));
   uint    uiEnd    = qvariant_cast<uint>(index.data(channellist::endRole));
   QIcon   icon     = qvariant_cast<QIcon>(index.data(channellist::iconRole));
#ifdef _TASTE_CHITRAM_TV
   // maybe we should think about to use these values for all brandings ...
   QSize   iconsize = icon.actualSize(QSize(42, 42));
#else
   QSize   iconsize = icon.actualSize(option.decorationSize);
#endif // _TASTE_CHITRAM_TV
   QString sChan    = qvariant_cast<QString>(index.data(channellist::nameRole));
   QString sProg    = qvariant_cast<QString>(index.data(channellist::progRole));
   QString sColor   = qvariant_cast<QString>(index.data(channellist::bgcolorRole));
   QString fromTo   = QString("%1 - %2")
                      .arg(QDateTime::fromTime_t(uiStart).toString("h:mm"))
                      .arg(QDateTime::fromTime_t(uiEnd).toString("h:mm"));
   /////////////////////////////////////////////////////////////////////////////

   // colorize background if this is a channel group ...
   if ((iCid == -1) && (sColor != "")
      && !(option.state & (QStyle::State_Selected | QStyle::State_MouseOver)))
   {
      // channel group ...
      painter->fillRect(option.rect, QColor(sColor));
   }

   // draw icon ...
   int   x = option.rect.x() + 2;
   int   y = option.rect.y() + ((option.rect.height() - iconsize.height()) / 2);
   QRect iconRect(x, y, iconsize.width(), iconsize.height());
   painter->drawPixmap(iconRect, icon.pixmap(iconsize));

   x = iconRect.right() + 4;
   int rightWidth = option.rect.right() - x - 2;

   // font stuff for channel line ...
   QFont chanFont = option.font;
   chanFont.setPointSize(chanFont.pointSize() + 1);
   chanFont.setBold(true);
   QFontMetrics fmChan(chanFont);

   // check if additional info is available ...
   if ((sProg == "") || !uiStart || !uiEnd)
   {
      // draw simple item only ...

      // channel line ...
      y = option.rect.y() + ((option.rect.height() - fmChan.height()) / 2);
      QRect chanRect(x, y, rightWidth, fmChan.height());

      painter->setFont(chanFont);
      painter->drawText(chanRect, Qt::TextSingleLine, sChan);
   }
   else
   {
      // draw advanced item ...
      QRect bounting;
      QFont progFont = option.font;
      progFont.setPointSize(progFont.pointSize() - 1);
      progFont.setWeight(progFont.weight() - 2);
      QFontMetrics fmProg(progFont);

      // channel line ...
      y = option.rect.y() + 2;
      QRect chanRect(x, y, rightWidth, fmChan.height());

      CSmallHelpers::cutProgString(sChan, fmChan, rightWidth);
      painter->setFont(chanFont);
      painter->drawText(chanRect, Qt::TextSingleLine, sChan, &bounting);

      // program line ...
      y = bounting.bottom();
      QRect progRect(x, y, rightWidth, fmProg.height());

      CSmallHelpers::cutProgString(sProg, fmProg, rightWidth);
      painter->setFont(progFont);
      painter->drawText(progRect, Qt::TextSingleLine, sProg.section('\n', 0, 0), &bounting);

      // from ... to line ...
      y = bounting.bottom();
      QRect timesRect(x, y, rightWidth, fmProg.height());
      painter->drawText(timesRect, Qt::TextSingleLine, fromTo, &bounting);

      // progress bar ...
      y = bounting.bottom() + 2;
      QRect progressRect(x, y, rightWidth, 5);
      iPos = (iPos > (int)(uiEnd - uiStart)) ? (int)(uiEnd - uiStart) : iPos;

#ifndef Q_OS_MAC
      QStyleOptionProgressBar progressBar;
      progressBar.rect        = progressRect;
      progressBar.minimum     = 0;
      progressBar.maximum     = (int)(uiEnd - uiStart);
      progressBar.progress    = iPos;
      progressBar.textVisible = false;

      QApplication::style()->drawControl(QStyle::CE_ProgressBar,
                                         &progressBar, painter);
#else
      // Drawing the progress bar on mac doesn't look nice
      // because the height can't be shrinked as needed.
      // So we try to draw our own progress bar here ...

      // make sure background is white ...
      painter->fillRect(progressRect, QColor("white"));

      // prepare pen for border line ...
      QPen pen(Qt::SolidLine);
      pen.setColor(QColor("silver"));
      pen.setWidth(1);
      painter->setPen(pen);

      // draw outline ...
      painter->drawRect(progressRect);

      // compute size of inner rect (take care of border) ...
      x = progressRect.width()  - pen.width();
      y = progressRect.height() - pen.width();
      x = (uiEnd - uiStart) ? ((x * iPos) / (int)(uiEnd - uiStart)) : 0; ///< avoid division with 0 !!!

      // inner rectangle (progess) ...
      QRect macRect(progressRect.x() + pen.width(), progressRect.y() + pen.width(), x, y);

      // paint progress ...
      painter->fillRect(macRect, QColor("#036"));
#endif // Q_OS_MAC

   }

   painter->restore();
}
/* -----------------------------------------------------------------\
|  Method: sizeHint
|  Begin:  22.03.2011 / 12:20
|  Author: Jo2003
|  Description: get size hint for custom list item
|
|  Parameters: view item, model index
|
|  Returns: size
\----------------------------------------------------------------- */
QSize QChanListDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
   int     iHeight, iWidth = 0, iTextHeight, iTextWidth[3];
   uint    uiStart  = qvariant_cast<uint>(index.data(channellist::startRole));
   uint    uiEnd    = qvariant_cast<uint>(index.data(channellist::endRole));
   QIcon   icon     = qvariant_cast<QIcon>(index.data(channellist::iconRole));
#ifdef _TASTE_CHITRAM_TV
   // maybe we should think about to use these values for all brandings ...
   QSize   iconsize = icon.actualSize(QSize(42, 42));
#else
   QSize   iconsize = icon.actualSize(option.decorationSize);
#endif // _TASTE_CHITRAM_TV
   QString sChan    = qvariant_cast<QString>(index.data(channellist::nameRole));
   QString sProg    = qvariant_cast<QString>(index.data(channellist::progRole));
   QString fromTo   = QString("%1 - %2")
                      .arg(QDateTime::fromTime_t(uiStart).toString("h:mm"))
                      .arg(QDateTime::fromTime_t(uiEnd).toString("h:mm"));

   iHeight = iconsize.height() + 4; // space on top and bottom ...

   QFont chanFont = option.font;
   chanFont.setPointSize(chanFont.pointSize() + 1);
   chanFont.setBold(true);

   QFontMetrics fmChan(chanFont);

   // check if additional info is available ...
   if ((sProg == "") || !uiStart || !uiEnd)
   {
      // no additional info --> simple item only ...
      iWidth       = fmChan.size(Qt::TextSingleLine, sChan).width();

      // take care of text height ...
      iTextHeight  = fmChan.height();

      if (iTextHeight > iHeight)
      {
         iHeight = iTextHeight;
      }
   }
   else
   {
      QFont progFont = option.font;
      progFont.setPointSize(progFont.pointSize() - 1);
      progFont.setWeight(progFont.weight() - 2);

      QFontMetrics fmProg(progFont);

      // "channel name" + "program" + "from ... to" ...
      iTextHeight  = fmChan.height() + fmProg.height() + fmProg.height();

      // add progress bar height ...
      iTextHeight += 10;

      if (iTextHeight > iHeight)
      {
         iHeight = iTextHeight;
      }

      // width ...
      CSmallHelpers::cutProgString(sProg, fmProg, option.rect.width() - (2 + iconsize.width() + 4 + 2));
      CSmallHelpers::cutProgString(sChan, fmChan, option.rect.width() - (2 + iconsize.width() + 4 + 2));
      iTextWidth[0] = fmChan.size(Qt::TextSingleLine, sChan).width();
      iTextWidth[1] = fmProg.size(Qt::TextSingleLine, sProg).width();
      iTextWidth[2] = fmProg.size(Qt::TextSingleLine, fromTo).width();

      for (int i = 0; i < 3; i++)
      {
         if (iTextWidth[i] > iWidth)
         {
            iWidth = iTextWidth[i];
         }
      }
   }

   iWidth += iconsize.width();
   iWidth += 4; // space between icon and text ...

   return QSize(iWidth, iHeight);
}
Exemple #21
0
//-----------------------------------------------------------------------------
void resizeColumnsToContents(QTreeWidget* tree, bool includeCollapsedItems)
{
  QList<QTreeWidgetItem*> collapsedItems;

  // If including collapsed items, first expand the entire tree
  if (includeCollapsedItems)
    {
    for (QTreeWidgetItemIterator iter(tree); *iter; ++iter)
      {
      QTreeWidgetItem* item = *iter;
      if (item->childCount() && !item->isExpanded())
        {
        item->setExpanded(true);
        collapsedItems.append(item);
        }
      }
    }

  int i = tree->columnCount();
  while (i--)
    {
    // Resize to data
    tree->resizeColumnToContents(i);

    // Also resize to header, if applicable
    if (!tree->isHeaderHidden())
      {
      // Get current size
      int cw = tree->columnWidth(i);

      // Get header text and icon
      QString text = tree->headerItem()->text(i);
      QIcon icon = tree->headerItem()->icon(i);

      // Get header font, using widget font if unset
      QFont font = tree->font();
      QVariant hfd = tree->headerItem()->data(i, Qt::FontRole);
      if (hfd.isValid() && hfd.canConvert(QVariant::Font))
        {
        font = hfd.value<QFont>();
        }

      // Calculate size of text and icon
      QFontMetrics fm(font);
      int tw = fm.width(text);
      if (!icon.isNull())
        {
        tw += icon.actualSize(tree->iconSize()).width();
        }

      // Add space for margins and sort indicator
      tw += 2 * tree->style()->pixelMetric(QStyle::PM_HeaderMargin);
      tw += 2 * tree->style()->pixelMetric(QStyle::PM_HeaderGripMargin);
      tw += tree->style()->pixelMetric(QStyle::PM_HeaderMarkSize);

      // Use header size, if larger
      if (tw > cw)
        {
        tree->setColumnWidth(i, tw);
        }
      }
    }

  // Restore collapsed state of anything we expanded
  foreach (QTreeWidgetItem* item, collapsedItems)
    item->setExpanded(false);
}