コード例 #1
0
void ActionComboBoxWidget::paintEvent(QPaintEvent *event)
{
	Q_UNUSED(event);

	QPainter painter(this);
	QStyleOptionComboBox comboBoxOption;
	comboBoxOption.initFrom(this);
	comboBoxOption.editable = false;

	style()->drawComplexControl(QStyle::CC_ComboBox, &comboBoxOption, &painter, this);

	QStyleOptionViewItem viewItemOption;
	viewItemOption.initFrom(this);
	viewItemOption.displayAlignment |= Qt::AlignVCenter;

	if (currentIndex() >= 0)
	{
		itemDelegate()->paint(&painter, viewItemOption, m_view->getModel()->index(currentIndex(), 0));
	}
	else
	{
		const int textMargin = (style()->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, this) + 1);

		painter.setFont(viewItemOption.font);
		painter.drawText(viewItemOption.rect.adjusted(textMargin, 0, -textMargin, 0), Qt::AlignVCenter, tr("Select Action"));
	}
}
コード例 #2
0
ファイル: kitemlistwidget.cpp プロジェクト: stream009/dolphin
void KItemListWidget::drawItemStyleOption(QPainter* painter, QWidget* widget, QStyle::State styleState)
{
    QStyleOptionViewItem viewItemOption;
    viewItemOption.initFrom(widget);
    viewItemOption.state = styleState;
    viewItemOption.viewItemPosition = QStyleOptionViewItem::OnlyOne;
    viewItemOption.showDecorationSelected = true;
    viewItemOption.rect = selectionRect().toRect();
    widget->style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &viewItemOption, painter, widget);
}
コード例 #3
0
void JumpToWidget::paintEvent(QPaintEvent *)
{
	this->setMinimumSize(23, _view->height());
	this->setMaximumSize(23, _view->height());
	QStylePainter p(this);
	QStyleOptionViewItem o;
	o.initFrom(_view);
	o.palette = QApplication::palette();
	p.fillRect(rect(), o.palette.window());

	QFont f = p.font();
	for (int i = 0; i < 26; i++) {
		p.save();
		QChar qc(i + 65);
		QRect r(0, height() * i / 26, 22, height() / 26);
		if (_currentLetter == qc) {
			// Display a bright selection rectangle corresponding to the top letter in the library
			p.fillRect(r, o.palette.highlight());
		} else if (o.state.testFlag(QStyle::State_MouseOver) && r.contains(_pos)) {
			// Display a light rectangle under the mouse pointer
			p.fillRect(r, o.palette.highlight().color().lighter(160));
		}
		if (o.state.testFlag(QStyle::State_MouseOver)) {
			QColor lighterBG = o.palette.highlight().color().lighter(160);
			QColor highlightedText = o.palette.highlightedText().color();
			if (qAbs(lighterBG.value() - highlightedText.value()) > 128) {
				p.setPen(highlightedText);
			} else {
				p.setPen(o.palette.windowText().color());
			}
		} else {
			p.setPen(o.palette.windowText().color());
		}
		if (_lettersToHighlight.contains(qc)) {
			p.save();
			f.setBold(true);
			p.setFont(f);
			p.drawText(r, Qt::AlignCenter, qc);
			p.restore();
		} else {
			p.drawText(r, Qt::AlignCenter, qc);
		}
		p.restore();
	}

	// Draw a vertical line if there are few items in the library
	if (!_view->verticalScrollBar()->isVisible()) {
		p.setPen(o.palette.mid().color());
		if (isLeftToRight()) {
			p.drawLine(rect().topRight(), rect().bottomRight());
		} else {
			p.drawLine(rect().topLeft(), rect().bottomLeft());
		}
	}
}
コード例 #4
0
ファイル: calculator.cpp プロジェクト: KDE/kalzium
calculator::calculator(QWidget *parent) : KDialog(parent)
{
    setWindowTitle(i18n("Chemical Calculator"));
    setButtons(Help | Close);
    setDefaultButton(Close);

    ui.setupUi(mainWidget());

    int maxTextWidth = 0;
    QStyleOptionViewItem option;
    option.initFrom(ui.tree);
    for (int i = 0; i < ui.tree->topLevelItemCount(); ++i) {
        maxTextWidth = qMax(maxTextWidth, ui.tree->itemDelegate()->sizeHint(option, ui.tree->model()->index(i, 0)).width());
    }
    // 20 because we want some margins, not a too tight text
    ui.tree->setMaximumWidth(qMax(ui.tree->maximumWidth(), maxTextWidth + 20));

    // Add the nuclear calculator to the user interface
    m_nuclearCalculator = new nuclearCalculator(this);
    ui.stack->addWidget(m_nuclearCalculator);
    // Add the gas calculator to the user interface
    m_gasCalculator = new gasCalculator(this);
    ui.stack->addWidget(m_gasCalculator);
    // Add the concentration calculator to the user interface
    m_concCalculator = new concCalculator(this);
    ui.stack->addWidget(m_concCalculator);
    // Add the molecular mass Calculator widget to the user interface
    m_moleCalculator = new MolcalcWidget(this);
    ui.stack->addWidget(m_moleCalculator);
    // Add the molecular mass Calculator widget to the user interface
    m_titraCalculator = new titrationCalculator(this);
    ui.stack->addWidget(m_titraCalculator);

#ifdef HAVE_FACILE
    // Add the equation balancer widget to the user interface
    QTreeWidgetItem *treeItem = new QTreeWidgetItem(ui.tree);
    treeItem->setText(0, i18n("Equation Balancer"));

    m_equationBalancer = new EQChemDialog(this);
    ui.stack->addWidget(m_equationBalancer);
#endif
    // Add an image to the file
    ui.pic->setPixmap((QIcon::fromTheme("calculate")).pixmap(128,128));

    // Connect the tree item selection signal to the corresponding slot
    connect(ui.tree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this,
            SLOT(slotItemSelection(QTreeWidgetItem*)));

    ui.tree->setCurrentItem(ui.tree->topLevelItem(0), 0, QItemSelectionModel::ToggleCurrent);

    // help clicked
    connect(this, SIGNAL(helpClicked()), this, SLOT(slotHelp()));
}
コード例 #5
0
/*!
 * \reimp{QFrame::paintEvent}
 */
void ImageItemWidget::paintEvent(QPaintEvent * e)
{
	if (selected)
	{
		QPainter painter(this);
		QStyleOptionViewItem opt;
		opt.initFrom(this);
		opt.backgroundBrush = Qt::transparent;
		opt.state |= QStyle::State_Selected;
		style()->drawControl(QStyle::CE_ItemViewItem, &opt, &painter, this);
	}
	QFrame::paintEvent(e);
}
コード例 #6
0
void KoResourceSelector::paintEvent( QPaintEvent *pe )
{
    QComboBox::paintEvent( pe );

    QStyleOptionComboBox option;
    option.initFrom( this );
    QRect r = style()->subControlRect( QStyle::CC_ComboBox, &option, QStyle::SC_ComboBoxEditField, this );

    QStyleOptionViewItem viewOption;
    viewOption.initFrom( this );
    viewOption.rect = r;
    
    QPainter painter( this );
    itemDelegate()->paint( &painter, viewOption, view()->currentIndex() );
}
コード例 #7
0
void 
FirehoseView::mouseDoubleClickEvent( QMouseEvent* e )
{
    QModelIndex i = indexAt( e->pos() );
    
    PlayableMimeData* data = PlayableMimeData::createFromUser( i.data().toString() );
    data->setImageData( i.data( Qt::DecorationRole ) );
    
    QStyleOptionViewItem options;
    options.initFrom( this );
    options.rect = visualRect( i );
    DelegateDragHint* dragHint = new DelegateDragHint( delegate, i, options, this );
    dragHint->setMimeData( data );
    
    dragHint->dragTo( The::mainWindow().ui.amp );
}
コード例 #8
0
QSize TestResultDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem opt = option;
    // make sure opt.rect is initialized correctly - otherwise we might get a width of 0
    opt.initFrom(opt.widget);
    initStyleOption(&opt, index);

    const QAbstractItemView *view = qobject_cast<const QAbstractItemView *>(opt.widget);
    const bool selected = view->selectionModel()->currentIndex() == index;

    QFontMetrics fm(opt.font);
    int fontHeight = fm.height();
    TestResultFilterModel *resultFilterModel = static_cast<TestResultFilterModel *>(view->model());
    LayoutPositions positions(opt, resultFilterModel);
    QSize s;
    s.setWidth(opt.rect.width());

    if (selected) {
        const TestResult &testResult = resultFilterModel->testResult(index);

        QString output = outputString(testResult, selected);
        output.replace(QLatin1Char('\n'), QChar::LineSeparator);

        if (AutotestPlugin::instance()->settings()->limitResultOutput
                && output.length() > outputLimit)
            output = output.left(outputLimit).append(QLatin1String("..."));

        recalculateTextLayout(index, output, opt.font, positions.textAreaWidth());

        s.setHeight(m_lastCalculatedHeight + 3);
    } else {
        s.setHeight(fontHeight + 3);
    }

    if (s.height() < positions.minimumHeight())
        s.setHeight(positions.minimumHeight());

    return s;
}
コード例 #9
0
/** @short Reimplemented to show custom pixmap during drag&drop

  Qt's model-view classes don't provide any means of interfering with the
  QDrag's pixmap so we just rip off QAbstractItemView::startDrag and provide
  our own QPixmap.
*/
void MsgListView::startDrag(Qt::DropActions supportedActions)
{
    // indexes for column 0, i.e. subject
    QModelIndexList baseIndexes;

    Q_FOREACH(const QModelIndex &index, selectedIndexes()) {
        if (!(model()->flags(index) & Qt::ItemIsDragEnabled))
            continue;
        if (index.column() == Imap::Mailbox::MsgListModel::SUBJECT)
            baseIndexes << index;
    }

    if (!baseIndexes.isEmpty()) {
        QMimeData *data = model()->mimeData(baseIndexes);
        if (!data)
            return;

        // use screen width and itemDelegate()->sizeHint() to determine size of the pixmap
        int screenWidth = QApplication::desktop()->screenGeometry(this).width();
        int maxWidth = qMax(400, screenWidth / 4);
        QSize size(maxWidth, 0);

        // Show a "+ X more items" text after so many entries
        const int maxItems = 20;

        QStyleOptionViewItem opt;
        opt.initFrom(this);
        opt.rect.setWidth(maxWidth);
        opt.rect.setHeight(itemDelegate()->sizeHint(opt, baseIndexes.at(0)).height());
        size.setHeight(qMin(maxItems + 1, baseIndexes.size()) * opt.rect.height());
        // State_Selected provides for nice background of the items
        opt.state |= QStyle::State_Selected;

        // paint list of selected items using itemDelegate() to be consistent with style
        QPixmap pixmap(size);
        pixmap.fill(Qt::transparent);
        QPainter p(&pixmap);

        for (int i = 0; i < baseIndexes.size(); ++i) {
            opt.rect.moveTop(i * opt.rect.height());
            if (i == maxItems) {
                p.fillRect(opt.rect, palette().color(QPalette::Disabled, QPalette::Highlight));
                p.setBrush(palette().color(QPalette::Disabled, QPalette::HighlightedText));
                p.drawText(opt.rect, Qt::AlignRight, tr("+ %n additional item(s)", 0, baseIndexes.size() - maxItems));
                break;
            }
            itemDelegate()->paint(&p, opt, baseIndexes.at(i));
        }

        QDrag *drag = new QDrag(this);
        drag->setPixmap(pixmap);
        drag->setMimeData(data);
        drag->setHotSpot(QPoint(0, 0));

        Qt::DropAction dropAction = Qt::IgnoreAction;
        if (defaultDropAction() != Qt::IgnoreAction && (supportedActions & defaultDropAction()))
            dropAction = defaultDropAction();
        else if (supportedActions & Qt::CopyAction && dragDropMode() != QAbstractItemView::InternalMove)
            dropAction = Qt::CopyAction;
        if (drag->exec(supportedActions, dropAction) == Qt::MoveAction) {
            // QAbstractItemView::startDrag calls d->clearOrRemove() here, so
            // this is a copy of QAbstractItemModelPrivate::clearOrRemove();
            const QItemSelection selection = selectionModel()->selection();
            QList<QItemSelectionRange>::const_iterator it = selection.constBegin();

            if (!dragDropOverwriteMode()) {
                for (; it != selection.constEnd(); ++it) {
                    QModelIndex parent = it->parent();
                    if (it->left() != 0)
                        continue;
                    if (it->right() != (model()->columnCount(parent) - 1))
                        continue;
                    int count = it->bottom() - it->top() + 1;
                    model()->removeRows(it->top(), count, parent);
                }
            } else {
                // we can't remove the rows so reset the items (i.e. the view is like a table)
                QModelIndexList list = selection.indexes();
                for (int i = 0; i < list.size(); ++i) {
                    QModelIndex index = list.at(i);
                    QMap<int, QVariant> roles = model()->itemData(index);
                    for (QMap<int, QVariant>::Iterator it = roles.begin(); it != roles.end(); ++it)
                        it.value() = QVariant();
                    model()->setItemData(index, roles);
                }
            }
        }
    }
}
コード例 #10
0
ファイル: kmessagebox.cpp プロジェクト: vasi/kdelibs
int KMessageBox::createKMessageBox(KDialog *dialog, const QIcon &icon,
                             const QString &text, const QStringList &strlist,
                             const QString &ask, bool *checkboxReturn, Options options,
                             const QString &details, QMessageBox::Icon notifyType)
{
    QWidget *mainWidget = new QWidget(dialog);
    QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget);
    mainLayout->setSpacing(KDialog::spacingHint() * 2); // provide extra spacing
    mainLayout->setMargin(0);

    QHBoxLayout *hLayout = new QHBoxLayout();
    hLayout->setMargin(0);
    hLayout->setSpacing(-1); // use default spacing
    mainLayout->addLayout(hLayout,5);

    QLabel *iconLabel = new QLabel(mainWidget);

    if (!icon.isNull()) {
        QStyleOption option;
        option.initFrom(mainWidget);
        iconLabel->setPixmap(icon.pixmap(mainWidget->style()->pixelMetric(QStyle::PM_MessageBoxIconSize, &option, mainWidget)));
    }

    QVBoxLayout *iconLayout = new QVBoxLayout();
    iconLayout->addStretch(1);
    iconLayout->addWidget(iconLabel);
    iconLayout->addStretch(5);

    hLayout->addLayout(iconLayout,0);
    hLayout->addSpacing(KDialog::spacingHint());

    QLabel *messageLabel = new QLabel(text, mainWidget);
    messageLabel->setOpenExternalLinks(options & KMessageBox::AllowLink);
    Qt::TextInteractionFlags flags = Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard;
    if (options & KMessageBox::AllowLink) {
        flags |= Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard;
    }
    messageLabel->setTextInteractionFlags(flags);

    QRect desktop = KGlobalSettings::desktopGeometry(dialog);
    bool usingSqueezedTextLabel = false;
    if (messageLabel->sizeHint().width() > desktop.width() * 0.5) {
        // enable automatic wrapping of messages which are longer than 50% of screen width
        messageLabel->setWordWrap(true);
        // display a text widget with scrollbar if still too wide
        usingSqueezedTextLabel = messageLabel->sizeHint().width() > desktop.width() * 0.85;
        if (usingSqueezedTextLabel)
        {
            delete messageLabel;
            messageLabel = new KSqueezedTextLabel(text, mainWidget);
            messageLabel->setOpenExternalLinks(options & KMessageBox::AllowLink);
            messageLabel->setTextInteractionFlags(flags);
        }
    }

    QPalette messagePal(messageLabel->palette());
    messagePal.setColor(QPalette::Window, Qt::transparent);
    messageLabel->setPalette(messagePal);


    bool usingScrollArea=desktop.height() / 3 < messageLabel->sizeHint().height();
    if (usingScrollArea)
    {
        QScrollArea* messageScrollArea = new QScrollArea(mainWidget);
        messageScrollArea->setWidget(messageLabel);
        messageScrollArea->setFrameShape(QFrame::NoFrame);
        messageScrollArea->setWidgetResizable(true);
        QPalette scrollPal(messageScrollArea->palette());
        scrollPal.setColor(QPalette::Window, Qt::transparent);
        messageScrollArea->viewport()->setPalette(scrollPal);
        hLayout->addWidget(messageScrollArea,5);
    }
    else
        hLayout->addWidget(messageLabel,5);


    const bool usingListWidget=!strlist.isEmpty();
    if (usingListWidget) {
        // enable automatic wrapping since the listwidget has already a good initial width
        messageLabel->setWordWrap(true);
        QListWidget *listWidget = new QListWidget(mainWidget);
        listWidget->addItems(strlist);

        QStyleOptionViewItem styleOption;
        styleOption.initFrom(listWidget);
        QFontMetrics fm(styleOption.font);
        int w = listWidget->width();
        Q_FOREACH(const QString &str, strlist) {
            w = qMax(w, fm.width(str));
        }
        const int borderWidth = listWidget->width() - listWidget->viewport()->width() + listWidget->verticalScrollBar()->height();
        w += borderWidth;
        if (w > desktop.width() * 0.85) { // limit listWidget size to 85% of screen width
            w = qRound(desktop.width() * 0.85);
        }
        listWidget->setMinimumWidth(w);

        mainLayout->addWidget(listWidget,usingScrollArea?10:50);
        listWidget->setSelectionMode(QListWidget::NoSelection);
        messageLabel->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Minimum);
    }
コード例 #11
0
ファイル: ddatetable.cpp プロジェクト: KDE/digikam
void DDateTable::paintCell(QPainter* painter, int row, int col)
{
    double w    = (width() / (double) d->numDayColumns) - 1;
    double h    = (height() / (double) d->numWeekRows) - 1;
    QRectF cell = QRectF(0, 0, w, h);
    QString cellText;
    QPen pen;
    QColor cellBackgroundColor, cellTextColor;
    QFont cellFont  = QFontDatabase::systemFont(QFontDatabase::GeneralFont);
    bool workingDay = false;
    int cellWeekDay, pos;

    //Calculate the position of the cell in the grid
    pos = d->numDayColumns * (row - 1) + col;

    //Calculate what day of the week the cell is
    if (col + locale().firstDayOfWeek() <= d->numDayColumns)
    {
        cellWeekDay = col + locale().firstDayOfWeek();
    }
    else
    {
        cellWeekDay = col + locale().firstDayOfWeek() - d->numDayColumns;
    }

    //FIXME This is wrong if the widget is not using the global!
    //See if cell day is normally a working day
    if (locale().weekdays().first() <= locale().weekdays().last())
    {
        if (cellWeekDay >= locale().weekdays().first() &&
            cellWeekDay <= locale().weekdays().last())
        {
            workingDay = true;
        }
    }
    else
    {
        if (cellWeekDay >= locale().weekdays().first() ||
            cellWeekDay <= locale().weekdays().last())
        {
            workingDay = true;
        }
    }

    if (row == 0)
    {
        //We are drawing a header cell

        //If not a normal working day, then use "do not work today" color
        if (workingDay)
        {
            cellTextColor = palette().color(QPalette::WindowText);
        }
        else
        {
            cellTextColor = Qt::darkRed;
        }

        cellBackgroundColor = palette().color(QPalette::Window);

        //Set the text to the short day name and bold it
        cellFont.setBold(true);
        cellText = locale().dayName(cellWeekDay, QLocale::ShortFormat);

    }
    else
    {
        //We are drawing a day cell

        //Calculate the date the cell represents
        QDate cellDate = dateFromPos(pos);
        bool validDay  = cellDate.isValid();

        // Draw the day number in the cell, if the date is not valid then we don't want to show it
        if (validDay)
        {
            cellText = QString::number(cellDate.day());
        }
        else
        {
            cellText = QLatin1String("");
        }

        if (! validDay || cellDate.month() != d->date.month())
        {
            // we are either
            // ° painting an invalid day
            // ° painting a day of the previous month or
            // ° painting a day of the following month or
            cellBackgroundColor = palette().color(backgroundRole());
            cellTextColor       = palette().color(QPalette::Disabled, QPalette::Text);
        }
        else
        {
            //Paint a day of the current month

            // Background Colour priorities will be (high-to-low):
            // * Selected Day Background Colour
            // * Customized Day Background Colour
            // * Normal Day Background Colour

            // Background Shape priorities will be (high-to-low):
            // * Customized Day Shape
            // * Normal Day Shape

            // Text Colour priorities will be (high-to-low):
            // * Customized Day Colour
            // * Day of Pray Colour (Red letter)
            // * Selected Day Colour
            // * Normal Day Colour

            //Determine various characteristics of the cell date
            bool selectedDay = (cellDate == date());
            bool currentDay  = (cellDate == QDate::currentDate());
            bool dayOfPray   = (cellDate.dayOfWeek() == Qt::Sunday);
            // TODO: Uncomment if QLocale ever gets the feature...
            //bool dayOfPray = ( cellDate.dayOfWeek() == locale().dayOfPray() );
            bool customDay   = (d->useCustomColors && d->customPaintingModes.contains(cellDate.toJulianDay()));

            //Default values for a normal cell
            cellBackgroundColor = palette().color(backgroundRole());
            cellTextColor = palette().color(foregroundRole());

            // If we are drawing the current date, then draw it bold and active
            if (currentDay)
            {
                cellFont.setBold(true);
                cellTextColor = palette().color(QPalette::LinkVisited);
            }

            // if we are drawing the day cell currently selected in the table
            if (selectedDay)
            {
                // set the background to highlighted
                cellBackgroundColor = palette().color(QPalette::Highlight);
                cellTextColor = palette().color(QPalette::HighlightedText);
            }

            //If custom colors or shape are required for this date
            if (customDay)
            {
                Private::DatePaintingMode mode = d->customPaintingModes[cellDate.toJulianDay()];

                if (mode.bgMode != NoBgMode)
                {
                    if (!selectedDay)
                    {
                        cellBackgroundColor = mode.bgColor;
                    }
                }

                cellTextColor = mode.fgColor;
            }

            //If the cell day is the day of religious observance, then always color text red unless Custom overrides
            if (! customDay && dayOfPray)
            {
                cellTextColor = Qt::darkRed;
            }

        }
    }

    //Draw the background
    if (row == 0)
    {
        painter->setPen(cellBackgroundColor);
        painter->setBrush(cellBackgroundColor);
        painter->drawRect(cell);
    }
    else if (cellBackgroundColor != palette().color(backgroundRole()) || pos == d->hoveredPos)
    {
        QStyleOptionViewItem opt;
        opt.initFrom(this);
        opt.rect = cell.toRect();

        if (cellBackgroundColor != palette().color(backgroundRole()))
        {
            opt.palette.setBrush(QPalette::Highlight, cellBackgroundColor);
            opt.state |= QStyle::State_Selected;
        }

        if (pos == d->hoveredPos && opt.state & QStyle::State_Enabled)
        {
            opt.state |= QStyle::State_MouseOver;
        }
        else
        {
            opt.state &= ~QStyle::State_MouseOver;
        }

        opt.showDecorationSelected = true;
        opt.viewItemPosition       = QStyleOptionViewItem::OnlyOne;
        style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, this);
    }

    //Draw the text
    painter->setPen(cellTextColor);
    painter->setFont(cellFont);
    painter->drawText(cell, Qt::AlignCenter, cellText, &cell);

    //Draw the base line
    if (row == 0)
    {
        painter->setPen(palette().color(foregroundRole()));
        painter->drawLine(QPointF(0, h), QPointF(w, h));
    }

    // If the day cell we just drew is bigger than the current max cell sizes,
    // then adjust the max to the current cell
    if (cell.width() > d->maxCell.width())
    {
        d->maxCell.setWidth(cell.width());
    }

    if (cell.height() > d->maxCell.height())
    {
        d->maxCell.setHeight(cell.height());
    }
}