Example #1
0
void QgsComposerHtml::loadHtml()
{
  if ( !mWebPage )
  {
    return;
  }

  QString loadedHtml;
  switch ( mContentMode )
  {
    case QgsComposerHtml::Url:
    {

      QString currentUrl = mUrl.toString();

      //data defined url set?
      QVariant exprVal;
      if ( dataDefinedEvaluate( QgsComposerObject::SourceUrl, exprVal ) )
      {
        currentUrl = exprVal.toString().trimmed();;
        QgsDebugMsg( QString( "exprVal Source Url:%1" ).arg( currentUrl ) );
      }
      if ( currentUrl.isEmpty() )
      {
        return;
      }
      if ( currentUrl != mLastFetchedUrl )
      {
        loadedHtml = fetchHtml( QUrl( currentUrl ) );
        mLastFetchedUrl = currentUrl;
      }
      else
      {
        loadedHtml = mFetchedHtml;
      }

      break;
    }
    case QgsComposerHtml::ManualHtml:
      loadedHtml = mHtml;
      break;
  }

  //evaluate expressions
  if ( mEvaluateExpressions )
  {
    loadedHtml = QgsExpression::replaceExpressionText( loadedHtml, mExpressionFeature, mExpressionLayer );
  }

  mLoaded = false;
  //set html, using the specified url as base if in Url mode
  mWebPage->mainFrame()->setHtml( loadedHtml, mContentMode == QgsComposerHtml::Url ? QUrl( mActualFetchedUrl ) : QUrl() );

  //set user stylesheet
  QWebSettings* settings = mWebPage->settings();
  if ( mEnableUserStylesheet && ! mUserStylesheet.isEmpty() )
  {
    QByteArray ba;
    ba.append( mUserStylesheet.toUtf8() );
    QUrl cssFileURL = QUrl( "data:text/css;charset=utf-8;base64," + ba.toBase64() );
    settings->setUserStyleSheetUrl( cssFileURL );
  }
  else
  {
    settings->setUserStyleSheetUrl( QUrl() );
  }

  while ( !mLoaded )
  {
    qApp->processEvents();
  }

  if ( frameCount() < 1 )  return;

  QSize contentsSize = mWebPage->mainFrame()->contentsSize();

  //find maximum frame width
  double maxFrameWidth = 0;
  QList<QgsComposerFrame*>::const_iterator frameIt = mFrameItems.constBegin();
  for ( ; frameIt != mFrameItems.constEnd(); ++frameIt )
  {
    maxFrameWidth = qMax( maxFrameWidth, ( *frameIt )->boundingRect().width() );
  }
  //set content width to match maximum frame width
  contentsSize.setWidth( maxFrameWidth * mHtmlUnitsToMM );

  mWebPage->setViewportSize( contentsSize );
  mWebPage->mainFrame()->setScrollBarPolicy( Qt::Horizontal, Qt::ScrollBarAlwaysOff );
  mWebPage->mainFrame()->setScrollBarPolicy( Qt::Vertical, Qt::ScrollBarAlwaysOff );
  mSize.setWidth( contentsSize.width() / mHtmlUnitsToMM );
  mSize.setHeight( contentsSize.height() / mHtmlUnitsToMM );

  renderCachedImage();

  recalculateFrameSizes();
  emit changed();
  //trigger a repaint
  emit contentsChanged();
}
Example #2
0
QSize MTButtonLabel::sizeHint() const
{
    QSize hint = QPushButton::sizeHint();
    hint.setWidth(hint.width() + 20);
    return hint;
}
Example #3
0
QSize FlowLayout::doLayout(QRect rect, bool apply) const
{
   //Configuration des marges
   int x,y=0; //Coordonnées courrantes
   int left, right, top, bottom; //Marge du layout
   int h=0; //Hauteur de la ligne courante
   int w;//Largeur du layout
   int nbe;//Nombre de widget expensible latéralement
   int p;//nom de pixel à rajouter aux widget expendable
   QSize s;

   auto it_b = items.begin(), end = items.end();
   auto it_e = it_b;

   getContentsMargins(&left, & top, &right, &bottom);

   if(m_d == Qt::LeftToRight)
   {
      w = rect.width() - right;
      y = rect.top() + top;
      left += rect.left();
      while(it_b != end)
      {
         nbe = (*it_b)->expandingDirections() & Qt::Horizontal;
         x = left;
         y += h;
         s = (*it_b)->sizeHint();
         x += s.width();
         h = s.height();
         it_e = it_b;
         while(x < w && (++it_e) != end)
         {
            nbe += (*it_e)->expandingDirections() & Qt::Horizontal;
            s = (*it_e)->sizeHint();
            x += s.width() + m_hs;
            if(h<s.height()) h = s.height();
         }
         if(it_e == it_b) ++it_e;
         if(it_e != end)
         {
            x -= s.width();
            nbe -= (*it_b)->expandingDirections() & Qt::Horizontal;
         }

         if(nbe)
         {
            p = (w-x) / nbe;
            nbe = (w-x) % nbe;
         }
         else p=0;

         if(apply)
         {
            x = left;
            while(it_b != it_e)
            {
               s = (*it_b)->sizeHint();
               s.setHeight(h);
               if(m_e && ((*it_b)->expandingDirections() & Qt::Horizontal))
               {
                  if(nbe)
                  {
                     --nbe;
                     s.rwidth() += p+1;
                  }
                  else s.rwidth() += p;
               }
               (*it_b)->setGeometry(QRect(QPoint(x,y),s));
               ++it_b;
               x += s.width() + m_hs;
            }
         }
         it_b = it_e;
         y += m_vs;
      }
   }
   s.setWidth(rect.width());
   s.setHeight(y+h+bottom);
   return s;
}
Example #4
0
QSize TabBar::tabSizeHint(int index, bool fast) const
{
    if (!isVisible() || !mApp->proxyStyle()) {
        // Don't calculate it when tabbar is not visible
        // It produces invalid size anyway
        //
        // We also need ProxyStyle to be set before calculating minimum sizes for tabs
        return QSize(-1, -1);
    }

    static int PINNED_TAB_WIDTH = comboTabBarPixelMetric(ComboTabBar::PinnedTabWidth);
    static int MINIMUM_ACTIVE_TAB_WIDTH = comboTabBarPixelMetric(ComboTabBar::ActiveTabMinimumWidth);
    static int MAXIMUM_TAB_WIDTH = comboTabBarPixelMetric(ComboTabBar::NormalTabMaximumWidth);
    static int MINIMUM_TAB_WIDTH = comboTabBarPixelMetric(ComboTabBar::NormalTabMinimumWidth);

    QSize size = ComboTabBar::tabSizeHint(index);

    // The overflowed tabs have same size and we can use this fast method
    if (fast) {
        size.setWidth(index >= pinnedTabsCount() ? MINIMUM_TAB_WIDTH : PINNED_TAB_WIDTH);
        return size;
    }

    WebTab* webTab = qobject_cast<WebTab*>(m_tabWidget->widget(index));
    TabBar* tabBar = const_cast <TabBar*>(this);

    if (webTab && webTab->isPinned()) {
        size.setWidth(PINNED_TAB_WIDTH);
    }
    else {
        int availableWidth = mainTabBarWidth() - comboTabBarPixelMetric(ExtraReservedWidth);

        if (availableWidth < 0) {
            return QSize(-1, -1);
        }

        const int normalTabsCount = ComboTabBar::normalTabsCount();

        if (availableWidth >= MAXIMUM_TAB_WIDTH * normalTabsCount) {
            m_normalTabWidth = MAXIMUM_TAB_WIDTH;
            size.setWidth(m_normalTabWidth);
        }
        else if (normalTabsCount > 0) {
            int maxWidthForTab = availableWidth / normalTabsCount;
            int realTabWidth = maxWidthForTab;
            bool adjustingActiveTab = false;

            if (realTabWidth < MINIMUM_ACTIVE_TAB_WIDTH) {
                maxWidthForTab = normalTabsCount > 1 ? (availableWidth - MINIMUM_ACTIVE_TAB_WIDTH) / (normalTabsCount - 1) : 0;
                realTabWidth = MINIMUM_ACTIVE_TAB_WIDTH;
                adjustingActiveTab = true;
            }

            bool tryAdjusting = availableWidth >= MINIMUM_TAB_WIDTH * normalTabsCount;

            if (m_showCloseOnInactive != 1 && tabsClosable() && availableWidth < (MINIMUM_TAB_WIDTH + 25) * normalTabsCount) {
                // Hiding close buttons to save some space
                tabBar->setTabsClosable(false);
                tabBar->showCloseButton(currentIndex());
            }
            if (m_showCloseOnInactive == 1) {
                // Always showing close buttons
                tabBar->setTabsClosable(true);
                tabBar->showCloseButton(currentIndex());
            }

            if (tryAdjusting) {
                m_normalTabWidth = maxWidthForTab;

                // Fill any empty space (we've got from rounding) with active tab
                if (index == mainTabBarCurrentIndex()) {
                    if (adjustingActiveTab) {
                        m_activeTabWidth = (availableWidth - MINIMUM_ACTIVE_TAB_WIDTH
                                            - maxWidthForTab * (normalTabsCount - 1)) + realTabWidth;
                    }
                    else {
                        m_activeTabWidth = (availableWidth - maxWidthForTab * normalTabsCount) + maxWidthForTab;
                    }
                    size.setWidth(m_activeTabWidth);
                }
                else {
                    size.setWidth(m_normalTabWidth);
                }
            }
        }

        // Restore close buttons according to preferences
        if (m_showCloseOnInactive != 2 && !tabsClosable() && availableWidth >= (MINIMUM_TAB_WIDTH + 25) * normalTabsCount) {
            tabBar->setTabsClosable(true);

            // Hide close buttons on pinned tabs
            for (int i = 0; i < count(); ++i) {
                tabBar->updatePinnedTabCloseButton(i);
            }
        }
    }

    if (index == count() - 1) {
        WebTab* lastMainActiveTab = qobject_cast<WebTab*>(m_tabWidget->widget(mainTabBarCurrentIndex()));
        int xForAddTabButton = cornerWidth(Qt::TopLeftCorner) + pinTabBarWidth() + normalTabsCount() * m_normalTabWidth;

        if (lastMainActiveTab && m_activeTabWidth > m_normalTabWidth) {
            xForAddTabButton += m_activeTabWidth - m_normalTabWidth;
        }

        if (QApplication::layoutDirection() == Qt::RightToLeft) {
            xForAddTabButton = width() - xForAddTabButton;
        }

        emit tabBar->moveAddTabButton(xForAddTabButton);
    }

    return size;
}
Example #5
0
QSize QDockWidgetLayout::sizeFromContent(const QSize &content, bool floating) const
{
    QSize result = content;

    if (verticalTitleBar) {
        result.setHeight(qMax(result.height(), minimumTitleWidth()));
        result.setWidth(qMax(content.width(), 0));
    } else {
        result.setHeight(qMax(result.height(), 0));
        result.setWidth(qMax(content.width(), minimumTitleWidth()));
    }

    QDockWidget *w = qobject_cast<QDockWidget*>(parentWidget());
    const bool nativeDeco = nativeWindowDeco(floating);

    int fw = floating && !nativeDeco
            ? w->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, 0, w)
            : 0;

    const int th = titleHeight();
    if (!nativeDeco) {
        if (verticalTitleBar)
            result += QSize(th + 2*fw, 2*fw);
        else
            result += QSize(2*fw, th + 2*fw);
    }

    result.setHeight(qMin(result.height(), (int) QWIDGETSIZE_MAX));
    result.setWidth(qMin(result.width(), (int) QWIDGETSIZE_MAX));

    if (content.width() < 0)
        result.setWidth(-1);
    if (content.height() < 0)
        result.setHeight(-1);

    int left, top, right, bottom;
    w->getContentsMargins(&left, &top, &right, &bottom);
    //we need to substract the contents margin (it will be added by the caller)
    QSize min = w->minimumSize() - QSize(left + right, top + bottom);
    QSize max = w->maximumSize() - QSize(left + right, top + bottom);

    /* A floating dockwidget will automatically get its minimumSize set to the layout's
       minimum size + deco. We're *not* interested in this, we only take minimumSize()
       into account if the user set it herself. Otherwise we end up expanding the result
       of a calculation for a non-floating dock widget to a floating dock widget's
       minimum size + window decorations. */

    uint explicitMin = 0;
    uint explicitMax = 0;
    if (w->d_func()->extra != 0) {
        explicitMin = w->d_func()->extra->explicitMinSize;
        explicitMax = w->d_func()->extra->explicitMaxSize;
    }

    if (!(explicitMin & Qt::Horizontal) || min.width() == 0)
        min.setWidth(-1);
    if (!(explicitMin & Qt::Vertical) || min.height() == 0)
        min.setHeight(-1);

    if (!(explicitMax & Qt::Horizontal))
        max.setWidth(QWIDGETSIZE_MAX);
    if (!(explicitMax & Qt::Vertical))
        max.setHeight(QWIDGETSIZE_MAX);

    return result.boundedTo(max).expandedTo(min);
}
//----------------------------------------------------------------------------
// Routines that handle Comma-Separated Values export file format.
//
QString timetrackerstorage::exportcsvFile(TaskView *taskview, const ReportCriteria &rc)
{
    kDebug(5970) << "Entering function";
    QString delim = rc.delimiter;
    QString dquote = rc.quote;
    QString double_dquote = dquote + dquote;
    bool to_quote = true;
    QString err;
    Task* task;
    int maxdepth=0;
    QString title = i18n("Export Progress");
    KProgressDialog dialog( taskview, 0, title );
    dialog.setAutoClose( true );
    dialog.setAllowCancel( true );
    dialog.progressBar()->setMaximum( 2 * taskview->count() );

    // The default dialog was not displaying all the text in the title bar.
    int width = taskview->fontMetrics().width(title) * 3;
    QSize dialogsize;
    dialogsize.setWidth(width);
    dialog.setInitialSize( dialogsize );

    if ( taskview->count() > 1 ) dialog.show();
    QString retval;

    // Find max task depth
    int tasknr = 0;
    while ( tasknr < taskview->count() && !dialog.wasCancelled() )
    {
        dialog.progressBar()->setValue( dialog.progressBar()->value() + 1 );
        if ( tasknr % 15 == 0 ) kapp->processEvents(); // repainting is slow
        if ( taskview->itemAt(tasknr)->depth() > maxdepth )
            maxdepth = taskview->itemAt(tasknr)->depth();
        tasknr++;
    }

    // Export to file
    tasknr = 0;
    while ( tasknr < taskview->count() && !dialog.wasCancelled() )
    {
        task = taskview->itemAt( tasknr );
        dialog.progressBar()->setValue( dialog.progressBar()->value() + 1 );
        if ( tasknr % 15 == 0 ) kapp->processEvents();

        // indent the task in the csv-file:
        for ( int i=0; i < task->depth(); ++i ) retval += delim;

        /*
        // CSV compliance
        // Surround the field with quotes if the field contains
        // a comma (delim) or a double quote
        if (task->name().contains(delim) || task->name().contains(dquote))
        to_quote = true;
        else
        to_quote = false;
        */
        to_quote = true;

        if (to_quote)
            retval += dquote;

        // Double quotes replaced by a pair of consecutive double quotes
        retval += task->name().replace( dquote, double_dquote );

        if (to_quote)
            retval += dquote;

        // maybe other tasks are more indented, so to align the columns:
        for ( int i = 0; i < maxdepth - task->depth(); ++i ) retval += delim;

        retval += delim + formatTime( task->sessionTime(),
                                   rc.decimalMinutes )
                + delim + formatTime( task->time(),
                                   rc.decimalMinutes )
                + delim + formatTime( task->totalSessionTime(),
                                   rc.decimalMinutes )
                + delim + formatTime( task->totalTime(),
                                   rc.decimalMinutes )
                + '\n';
        tasknr++;
    }

    // save, either locally or remote
    if ((rc.url.isLocalFile()) || (!rc.url.url().contains("/")))
    {
        QString filename=rc.url.toLocalFile();
        if (filename.isEmpty()) filename=rc.url.url();
        QFile f( filename );
        if( !f.open( QIODevice::WriteOnly ) )
        {
            err = i18n( "Could not open \"%1\".", filename );
        }
        if (err.length()==0)
        {
            QTextStream stream(&f);
            // Export to file
            stream << retval;
            f.close();
        }
    }
    else // use remote file
    {
        KTemporaryFile tmpFile;
        if ( !tmpFile.open() ) err = QString::fromLatin1( "Unable to get temporary file" );
        else
        {
            QTextStream stream ( &tmpFile );
            stream << retval;
            stream.flush();
            if (!KIO::NetAccess::upload( tmpFile.fileName(), rc.url, 0 )) err=QString::fromLatin1("Could not upload");
        }
    }

    return err;
}
Example #7
0
bool SizeFitter::fitIt(QSize size, QSize &fittedSize, QRect *clippedRect) const
{
    float scaleFactor;
    bool  result;
    QSize orientedTargetSize = getOrientedTargetSize(size);

    // enlarge?
    if (!isFitOptionEnabled(FitOption::Enlarge) &&
        size.width() <= orientedTargetSize.width() &&
        size.height() <= orientedTargetSize.height()) {
        fittedSize = size;
        if (clippedRect != nullptr) {
            clippedRect->setTopLeft(QPoint(0, 0));
            clippedRect->setSize(fittedSize);
        }
        return false;
    }

    result = false;
    if (size.width() > size.height()) {
        // landscape        
        scaleFactor = (float)orientedTargetSize.width() / (float)size.width();
        fittedSize.setWidth(qRound(size.width() * scaleFactor));
        fittedSize.setHeight(qRound(size.height() * scaleFactor));

        if (scaleFactor != 1.0f) {
            result = true;
        }

        // the new height might still be too large...
        if (fittedSize.height() > orientedTargetSize.height()) {
            // ...so scale again
            scaleFactor = (float)orientedTargetSize.height() / (float)fittedSize.height();
            fittedSize.setWidth (qRound(fittedSize.width() * scaleFactor));
            fittedSize.setHeight(qRound(fittedSize.height() * scaleFactor));
            
            if (scaleFactor != 1.0f) {
                result = true ;
            }
        }
    } else {
        // portrait        
        scaleFactor = (float)orientedTargetSize.height() / (float)size.height();
        fittedSize.setWidth (qRound(size.width() * scaleFactor));
        fittedSize.setHeight (qRound(size.height() * scaleFactor));

        if (scaleFactor != 1.0f) {
            result = true;
        }

        // the new width might still be too large...
        if (fittedSize.width() > orientedTargetSize.width()) {

            // ...so scale again
            scaleFactor = (float)orientedTargetSize.width() / (float)fittedSize.width();
            fittedSize.setWidth (qRound(fittedSize.width() * scaleFactor));
            fittedSize.setHeight (qRound(fittedSize.height() * scaleFactor));

            if (scaleFactor != 1.0f) {
                result = true ;
            }            
        }
    }

    if (clippedRect != nullptr) {
        // no clipping, select entire image
        clippedRect->setTopLeft(QPoint(0, 0));
        clippedRect->setSize(size);
    }

    return result;

}
Example #8
0
void PageLayoutDialog::accept()
{
    PrintSettings settings;
    settings.setPageLayout(pageLayout());
    settings.setPrintGrid(d->sheetPage.gridCheckBox->isChecked());
    settings.setPrintCommentIndicator(d->sheetPage.commentCheckBox->isChecked());
    settings.setPrintFormulaIndicator(d->sheetPage.formulaCheckBox->isChecked());
    settings.setPrintCharts(d->sheetPage.chartsCheckBox->isChecked());
    settings.setPrintGraphics(d->sheetPage.drawingsCheckBox->isChecked());
    settings.setPrintObjects(d->sheetPage.objectsCheckBox->isChecked());
    settings.setPrintZeroValues(d->sheetPage.zeroValuesCheckBox->isChecked());
    settings.setPrintHeaders(d->sheetPage.headersCheckBox->isChecked());
    settings.setPageOrder(d->sheetPage.ltrButton->isChecked() ? PrintSettings::LeftToRight : PrintSettings::TopToBottom);
    settings.setCenterHorizontally(d->sheetPage.horizontalCheckBox->isChecked());
    settings.setCenterVertically(d->sheetPage.verticalCheckBox->isChecked());

    // Set the repeated columns.
    if (d->sheetPage.columnsCheckBox->isChecked()) {
        // TODO Stefan: Check if width of repeated columns exceeds page width.
        const int startColumn = Util::decodeColumnLabelText(d->sheetPage.startColumnComboBox->currentText());
        const int endColumn = Util::decodeColumnLabelText(d->sheetPage.endColumnComboBox->currentText());
        settings.setRepeatedColumns(qMakePair(qMin(startColumn, endColumn), qMax(startColumn, endColumn)));
    } else
        settings.setRepeatedColumns(QPair<int, int>());

    // Set the repeated rows.
    if (d->sheetPage.rowsCheckBox->isChecked()) {
        // TODO Stefan: Check if height of repeated rows exceeds page height.
        const int startRow = d->sheetPage.startRowComboBox->currentText().toInt();
        const int endRow = d->sheetPage.endRowComboBox->currentText().toInt();
        settings.setRepeatedRows(qMakePair(qMin(startRow, endRow), qMax(startRow, endRow)));
    } else
        settings.setRepeatedRows(QPair<int, int>());

    bool isValid = false;
    settings.setZoom(0.01 * d->sheetPage.zoomComboBox->currentText().remove('%').toDouble(&isValid));
    if (!isValid)
        settings.setZoom(1.0);

    QSize pageLimits;
    if (d->sheetPage.pageLimitsButton->isChecked()) {
        pageLimits.setWidth(d->sheetPage.horizontalComboBox->currentText().toInt(&isValid));
        if (!isValid)
            pageLimits.setWidth(0);
        pageLimits.setHeight(d->sheetPage.verticalComboBox->currentText().toInt(&isValid));
        if (!isValid)
            pageLimits.setHeight(0);
    }
    settings.setPageLimits(pageLimits);

    if (applyToDocument()) {
        // Apply to all sheets.
        KUndo2Command* macroCommand = new KUndo2Command(kundo2_i18n("Set Page Layout"));
        const QList<Sheet*> sheets = d->sheet->map()->sheetList();
        for (int i = 0; i < sheets.count(); ++i) {
            PageLayoutCommand* command = new PageLayoutCommand(sheets[i], settings, macroCommand);
            Q_UNUSED(command);
        }
        d->sheet->doc()->addCommand(macroCommand);
    } else {
        PageLayoutCommand* command = new PageLayoutCommand(d->sheet, settings);
        d->sheet->doc()->addCommand(command);
    }

    KoPageLayoutDialog::accept();
}
DisplayFilterEdit::DisplayFilterEdit(QWidget *parent, bool plain) :
    SyntaxLineEdit(parent),
    plain_(plain),
    field_name_only_(false)
{
    setAccessibleName(tr("Display filter entry"));

    if (plain_) {
        empty_filter_message_ = QString(tr("Enter a display filter %1")).arg(UTF8_HORIZONTAL_ELLIPSIS);
    } else {
        empty_filter_message_ = QString(tr("Apply a display filter %1 <%2/>")).arg(UTF8_HORIZONTAL_ELLIPSIS)
    .arg(DEFAULT_MODIFIER);
    }

    //   DFCombo
    //     Bookmark (star)
    //     DispalyFilterEdit
    //     Clear button
    //     Apply (right arrow) + Cancel (x) + Reload (arrowed circle)
    //     Down Arrow

    // XXX - Move bookmark and apply buttons to the toolbar a la Firefox, Chrome & Safari?
    // XXX - Use native buttons on OS X?

    bookmark_button_ = new QToolButton(this);
    bookmark_button_->setCursor(Qt::ArrowCursor);
    bookmark_button_->setStyleSheet(QString(
            "QToolButton { /* all types of tool button */"
            "  border 0 0 0 0;"
            "  border-right: %1px solid gray;"
            "  border-top-left-radius: 3px;"
            "  border-bottom-left-radius: 3px;"
            "  padding-left: 1px;"
            "  image: url(:/dfilter/dfilter_bookmark_normal.png);"
//            "  background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
//            "                                      stop: 0 #f6f7fa, stop: 1 #dadbde);"
            "}"

            "QToolButton:hover {"
            "  image: url(:/dfilter/dfilter_bookmark_hover.png);"
            "}"
            "QToolButton:pressed {"
            "  image: url(:/dfilter/dfilter_bookmark_pressed.png);"
            "}"

//            "QToolButton:pressed {"
//            "    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
//            "                                      stop: 0 #dadbde, stop: 1 #f6f7fa);"
//            "}"

            ).arg(plain_ ? 0 : 1)
            );
    connect(bookmark_button_, SIGNAL(clicked()), this, SLOT(showDisplayFilterDialog()));

    clear_button_ = new QToolButton(this);
    clear_button_->setCursor(Qt::ArrowCursor);
    clear_button_->setStyleSheet(
            "QToolButton {"
            "  image: url(:/dfilter/dfilter_erase_normal.png);"
            "  border: none;"
            "  width: 16px;"
            "}"
            "QToolButton:hover {"
            "  image: url(:/dfilter/dfilter_erase_active.png);"
            "}"
            "QToolButton:pressed {"
            "  image: url(:/dfilter/dfilter_erase_selected.png);"
            "}"
            );
    clear_button_->hide();
    connect(clear_button_, SIGNAL(clicked()), this, SLOT(clear()));
    connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(checkFilter(const QString&)));

    apply_button_ = NULL;
    if (!plain_) {
        apply_button_ = new QToolButton(this);
        apply_button_->setCursor(Qt::ArrowCursor);
        apply_button_->setStyleSheet(
                "QToolButton { /* all types of tool button */"
                "  border 0 0 0 0;"
                "  border-top-right-radius: 3px;"
                "  border-bottom-right-radius: 3px;"
                "  padding-right: 1px;"
                "  image: url(:/dfilter/dfilter_apply_normal.png);"
                "}"

                "QToolButton:hover {"
                "  image: url(:/dfilter/dfilter_apply_hover.png);"
                "}"
                "QToolButton:pressed {"
                "  image: url(:/dfilter/dfilter_apply_pressed.png);"
                "}"
                );
        connect(apply_button_, SIGNAL(clicked()), this, SLOT(applyDisplayFilter()));
        connect(this, SIGNAL(returnPressed()), this, SLOT(applyDisplayFilter()));
    }

    int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
    QSize bksz = bookmark_button_->sizeHint();
    QSize cbsz = clear_button_->sizeHint();
    QSize apsz;
    if (apply_button_) {
        apsz = apply_button_->sizeHint();
    } else {
        apsz.setHeight(0); apsz.setWidth(0);
    }
    setStyleSheet(QString(
            "DisplayFilterEdit {"
            "  padding-left: %1px;"
            "  margin-left: %2px;"
            "  margin-right: %3px;"
            "}"
            )
            .arg(frameWidth + 1)
            .arg(bksz.width())
            .arg(cbsz.width() + apsz.width() + frameWidth + 1)
            );
}
QSize CategoryFilterWidget::minimumSizeHint() const
{
    QSize size = sizeHint();
    size.setWidth(6);
    return size;
}
Example #11
0
QSize FlexiTableView::sizeHint() const
{
	QSize size = QTableView::sizeHint();
	size.setWidth(200);
	return size;
}
Example #12
0
int TmxRasterizer::render(const QString &mapFileName,
                          const QString &imageFileName)
{
    MapReader reader;
    std::unique_ptr<Map> map { reader.readMap(mapFileName) };
    if (!map) {
        qWarning("Error while reading \"%s\":\n%s",
                 qUtf8Printable(mapFileName),
                 qUtf8Printable(reader.errorString()));
        return 1;
    }

    std::unique_ptr<MapRenderer> renderer;

    switch (map->orientation()) {
    case Map::Isometric:
        renderer.reset(new IsometricRenderer(map.get()));
        break;
    case Map::Staggered:
        renderer.reset(new StaggeredRenderer(map.get()));
        break;
    case Map::Hexagonal:
        renderer.reset(new HexagonalRenderer(map.get()));
        break;
    case Map::Orthogonal:
    default:
        renderer.reset(new OrthogonalRenderer(map.get()));
        break;
    }

    QRect mapBoundingRect = renderer->mapBoundingRect();
    QSize mapSize = mapBoundingRect.size();
    QPoint mapOffset = mapBoundingRect.topLeft();
    qreal xScale, yScale;

    if (mSize > 0) {
        xScale = (qreal) mSize / mapSize.width();
        yScale = (qreal) mSize / mapSize.height();
        xScale = yScale = qMin(1.0, qMin(xScale, yScale));
    } else if (mTileSize > 0) {
        xScale = (qreal) mTileSize / map->tileWidth();
        yScale = (qreal) mTileSize / map->tileHeight();
    } else {
        xScale = yScale = mScale;
    }

    QMargins margins = map->computeLayerOffsetMargins();
    mapSize.setWidth(mapSize.width() + margins.left() + margins.right());
    mapSize.setHeight(mapSize.height() + margins.top() + margins.bottom());

    mapSize.rwidth() *= xScale;
    mapSize.rheight() *= yScale;

    QImage image(mapSize, QImage::Format_ARGB32);
    image.fill(Qt::transparent);
    QPainter painter(&image);

    painter.setRenderHint(QPainter::Antialiasing, mUseAntiAliasing);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, mSmoothImages);
    painter.setTransform(QTransform::fromScale(xScale, yScale));

    painter.translate(margins.left(), margins.top());
    painter.translate(-mapOffset);

    // Perform a similar rendering than found in exportasimagedialog.cpp
    LayerIterator iterator(map.get());
    while (const Layer *layer = iterator.next()) {
        if (!shouldDrawLayer(layer))
            continue;

        const auto offset = layer->totalOffset();

        painter.setOpacity(layer->effectiveOpacity());
        painter.translate(offset);

        const TileLayer *tileLayer = dynamic_cast<const TileLayer*>(layer);
        const ImageLayer *imageLayer = dynamic_cast<const ImageLayer*>(layer);

        if (tileLayer) {
            renderer->drawTileLayer(&painter, tileLayer);
        } else if (imageLayer) {
            renderer->drawImageLayer(&painter, imageLayer);
        }

        painter.translate(-offset);
    }

    map.reset();

    // Save image
    QImageWriter imageWriter(imageFileName);

    if (!imageWriter.canWrite())
        imageWriter.setFormat("png");

    if (!imageWriter.write(image)) {
        qWarning("Error while writing \"%s\": %s",
                 qUtf8Printable(imageFileName),
                 qUtf8Printable(imageWriter.errorString()));
        return 1;
    }

    return 0;
}
Example #13
0
QSize DotLabel::minimumSizeHint() const {
    QSize s = QLabel::minimumSizeHint();
    s.setWidth(-1);
    return s;
}
void DirectShowMetaDataControl::updateMetadata(IFilterGraph2 *graph, IBaseFilter *source, const QString &fileSrc)
{
    m_metadata.clear();

#ifndef QT_NO_SHELLITEM
    if (!sHCreateItemFromParsingName) {
        QSystemLibrary lib(QStringLiteral("shell32"));
        sHCreateItemFromParsingName = (q_SHCreateItemFromParsingName)(lib.resolve("SHCreateItemFromParsingName"));
    }

    if (!fileSrc.isEmpty() && sHCreateItemFromParsingName) {
        IShellItem2* shellItem = 0;
        if (sHCreateItemFromParsingName(reinterpret_cast<const WCHAR*>(fileSrc.utf16()),
                                        0, IID_PPV_ARGS(&shellItem)) == S_OK) {

            IPropertyStore *pStore = 0;
            if (shellItem->GetPropertyStore(GPS_DEFAULT, IID_PPV_ARGS(&pStore)) == S_OK) {
                DWORD cProps;
                if (SUCCEEDED(pStore->GetCount(&cProps))) {
                    for (DWORD i = 0; i < cProps; ++i)
                    {
                        PROPERTYKEY key;
                        PROPVARIANT var;
                        PropVariantInit(&var);
                        if (FAILED(pStore->GetAt(i, &key)))
                            continue;
                        if (FAILED(pStore->GetValue(key, &var)))
                            continue;

                        if (IsEqualPropertyKey(key, PKEY_Author)) {
                            m_metadata.insert(QMediaMetaData::Author, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Title)) {
                            m_metadata.insert(QMediaMetaData::Title, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Media_SubTitle)) {
                            m_metadata.insert(QMediaMetaData::SubTitle, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_ParentalRating)) {
                            m_metadata.insert(QMediaMetaData::ParentalRating, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Comment)) {
                            m_metadata.insert(QMediaMetaData::Description, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Copyright)) {
                            m_metadata.insert(QMediaMetaData::Copyright, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Media_ProviderStyle)) {
                            m_metadata.insert(QMediaMetaData::Genre, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Media_Year)) {
                            m_metadata.insert(QMediaMetaData::Year, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Media_DateEncoded)) {
                            m_metadata.insert(QMediaMetaData::Date, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Rating)) {
                            m_metadata.insert(QMediaMetaData::UserRating,
                                              int((convertValue(var).toUInt() - 1) / qreal(98) * 100));
                        } else if (IsEqualPropertyKey(key, PKEY_Keywords)) {
                            m_metadata.insert(QMediaMetaData::Keywords, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Language)) {
                            m_metadata.insert(QMediaMetaData::Language, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Media_Publisher)) {
                            m_metadata.insert(QMediaMetaData::Publisher, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Media_Duration)) {
                            m_metadata.insert(QMediaMetaData::Duration,
                                              (convertValue(var).toLongLong() + 10000) / 10000);
                        } else if (IsEqualPropertyKey(key, PKEY_Audio_EncodingBitrate)) {
                            m_metadata.insert(QMediaMetaData::AudioBitRate, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Media_AverageLevel)) {
                            m_metadata.insert(QMediaMetaData::AverageLevel, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Audio_ChannelCount)) {
                            m_metadata.insert(QMediaMetaData::ChannelCount, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Audio_PeakValue)) {
                            m_metadata.insert(QMediaMetaData::PeakValue, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Audio_SampleRate)) {
                            m_metadata.insert(QMediaMetaData::SampleRate, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Music_AlbumTitle)) {
                            m_metadata.insert(QMediaMetaData::AlbumTitle, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Music_AlbumArtist)) {
                            m_metadata.insert(QMediaMetaData::AlbumArtist, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Music_Artist)) {
                            m_metadata.insert(QMediaMetaData::ContributingArtist, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Music_Composer)) {
                            m_metadata.insert(QMediaMetaData::Composer, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Music_Conductor)) {
                            m_metadata.insert(QMediaMetaData::Conductor, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Music_Lyrics)) {
                            m_metadata.insert(QMediaMetaData::Lyrics, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Music_Mood)) {
                            m_metadata.insert(QMediaMetaData::Mood, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Music_TrackNumber)) {
                            m_metadata.insert(QMediaMetaData::TrackNumber, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Music_Genre)) {
                            m_metadata.insert(QMediaMetaData::Genre, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_ThumbnailStream)) {
                            m_metadata.insert(QMediaMetaData::ThumbnailImage, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Video_FrameHeight)) {
                            QSize res;
                            res.setHeight(convertValue(var).toUInt());
                            if (SUCCEEDED(pStore->GetValue(PKEY_Video_FrameWidth, &var)))
                                res.setWidth(convertValue(var).toUInt());
                            m_metadata.insert(QMediaMetaData::Resolution, res);
                        } else if (IsEqualPropertyKey(key, PKEY_Video_HorizontalAspectRatio)) {
                            QSize aspectRatio;
                            aspectRatio.setWidth(convertValue(var).toUInt());
                            if (SUCCEEDED(pStore->GetValue(PKEY_Video_VerticalAspectRatio, &var)))
                                aspectRatio.setHeight(convertValue(var).toUInt());
                            m_metadata.insert(QMediaMetaData::PixelAspectRatio, aspectRatio);
                        } else if (IsEqualPropertyKey(key, PKEY_Video_FrameRate)) {
                            m_metadata.insert(QMediaMetaData::VideoFrameRate,
                                              convertValue(var).toReal() / 1000);
                        } else if (IsEqualPropertyKey(key, PKEY_Video_EncodingBitrate)) {
                            m_metadata.insert(QMediaMetaData::VideoBitRate, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Video_Director)) {
                            m_metadata.insert(QMediaMetaData::Director, convertValue(var));
                        } else if (IsEqualPropertyKey(key, PKEY_Media_Writer)) {
                            m_metadata.insert(QMediaMetaData::Writer, convertValue(var));
                        }

                        PropVariantClear(&var);
                    }
                }

                pStore->Release();
            }

            shellItem->Release();
        }
    }

    if (!m_metadata.isEmpty())
        goto send_event;
#endif

#ifndef QT_NO_WMSDK
    IWMHeaderInfo *info = com_cast<IWMHeaderInfo>(source, IID_IWMHeaderInfo);

    if (info) {
        Q_FOREACH (const QWMMetaDataKey &key, *qt_wmMetaDataKeys()) {
            QVariant var = getValue(info, key.wmName);
            if (var.isValid()) {
                if (key.qtName == QMediaMetaData::Duration) {
                    // duration is provided in 100-nanosecond units, convert to milliseconds
                    var = (var.toLongLong() + 10000) / 10000;
                } else if (key.qtName == QMediaMetaData::Resolution) {
                    QSize res;
                    res.setHeight(var.toUInt());
                    res.setWidth(getValue(info, L"WM/VideoWidth").toUInt());
                    var = res;
                } else if (key.qtName == QMediaMetaData::VideoFrameRate) {
                    var = var.toReal() / 1000.f;
                } else if (key.qtName == QMediaMetaData::PixelAspectRatio) {
                    QSize aspectRatio;
                    aspectRatio.setWidth(var.toUInt());
                    aspectRatio.setHeight(getValue(info, L"AspectRatioY").toUInt());
                    var = aspectRatio;
                } else if (key.qtName == QMediaMetaData::UserRating) {
                    var = (var.toUInt() - 1) / qreal(98) * 100;
                }

                m_metadata.insert(key.qtName, var);
            }
        }

        info->Release();
    }

    if (!m_metadata.isEmpty())
        goto send_event;
#endif
    {
        IAMMediaContent *content = 0;

        if ((!graph || graph->QueryInterface(
                 IID_IAMMediaContent, reinterpret_cast<void **>(&content)) != S_OK)
                && (!source || source->QueryInterface(
                        IID_IAMMediaContent, reinterpret_cast<void **>(&content)) != S_OK)) {
            content = 0;
        }

        if (content) {
            BSTR string = 0;

            if (content->get_AuthorName(&string) == S_OK)
                m_metadata.insert(QMediaMetaData::Author, convertBSTR(&string));

            if (content->get_Title(&string) == S_OK)
                m_metadata.insert(QMediaMetaData::Title, convertBSTR(&string));

            if (content->get_Description(&string) == S_OK)
                m_metadata.insert(QMediaMetaData::Description, convertBSTR(&string));

            if (content->get_Rating(&string) == S_OK)
                m_metadata.insert(QMediaMetaData::UserRating, convertBSTR(&string));

            if (content->get_Copyright(&string) == S_OK)
                m_metadata.insert(QMediaMetaData::Copyright, convertBSTR(&string));

            content->Release();
        }
    }

send_event:
    // DirectShowMediaPlayerService holds a lock at this point so defer emitting signals to a later
    // time.
    QCoreApplication::postEvent(this, new QEvent(QEvent::Type(MetaDataChanged)));
}
Example #15
0
//Gets the current predicted angles from the oculus sensors
void OculusManager::getEulerAngles(float& yaw, float& pitch, float& roll) {
#ifdef HAVE_LIBOVR
#if defined(__APPLE__) || defined(_WIN32)
    ovrTrackingState ts = ovrHmd_GetTrackingState(_ovrHmd, ovr_GetTimeInSeconds());
#else
    ovrSensorState ss = ovrHmd_GetSensorState(_ovrHmd, _hmdFrameTiming.ScanoutMidpointSeconds);
#endif
#if defined(__APPLE__) || defined(_WIN32) 
    if (ts.StatusFlags & (ovrStatus_OrientationTracked | ovrStatus_PositionTracked)) {
#else
    if (ss.StatusFlags & (ovrStatus_OrientationTracked | ovrStatus_PositionTracked)) {
#endif
        
#if defined(__APPLE__) || defined(_WIN32)
        ovrPosef headPose = ts.HeadPose.ThePose;
#else
        ovrPosef headPose = ss.Predicted.Pose;
#endif
        Quatf orientation = Quatf(headPose.Orientation);
        orientation.GetEulerAngles<Axis_Y, Axis_X, Axis_Z, Rotate_CCW, Handed_R>(&yaw, &pitch, &roll);
    } else {
        yaw = 0.0f;
        pitch = 0.0f;
        roll = 0.0f;
    }
#else
    yaw = 0.0f;
    pitch = 0.0f;
    roll = 0.0f;
#endif
}
    
glm::vec3 OculusManager::getRelativePosition() {
#if (defined(__APPLE__) || defined(_WIN32)) && HAVE_LIBOVR
    ovrTrackingState trackingState = ovrHmd_GetTrackingState(_ovrHmd, ovr_GetTimeInSeconds());
    ovrVector3f headPosition = trackingState.HeadPose.ThePose.Position;
    
    return glm::vec3(headPosition.x, headPosition.y, headPosition.z);
#else
    // no positional tracking in Linux yet
    return glm::vec3(0.0f, 0.0f, 0.0f);
#endif
}

//Used to set the size of the glow framebuffers
QSize OculusManager::getRenderTargetSize() {
#ifdef HAVE_LIBOVR
    QSize rv;
    rv.setWidth(_renderTargetSize.w);
    rv.setHeight(_renderTargetSize.h);
    return rv;
#else
    return QSize(100, 100);
#endif
}

void OculusManager::overrideOffAxisFrustum(float& left, float& right, float& bottom, float& top, float& nearVal,
        float& farVal, glm::vec4& nearClipPlane, glm::vec4& farClipPlane) {
#ifdef HAVE_LIBOVR
    if (_activeEyeIndex != -1) {
        const ovrFovPort& port = _eyeFov[_activeEyeIndex];
        right = nearVal * port.RightTan;
        left = -nearVal * port.LeftTan;
        top = nearVal * port.UpTan;
        bottom = -nearVal * port.DownTan;
    }
#endif
}
Example #16
0
    bool drawText(const char * pszText, QSize& size, const FontDefinition &textDefinition, const char * pFontName = NULL, int fontSize = 0)
    {
        bool nRet = false;
        do
        {
            CC_BREAK_IF(pszText == NULL || strlen(pszText) <= 0);

            // Set font
            std::string fontName = pFontName;

            if (fontName.c_str())
            {
                int nFindttf = fontName.find(".ttf");
                int nFindTTF = fontName.find(".TTF");
                if (nFindttf >= 0 || nFindTTF >= 0)
                {
                    QFontDatabase::addApplicationFont(fontName.c_str());

                    // delete .ttf suffix from fontName
                    int nFindPos = fontName.rfind("/");
                    fontName = &fontName[nFindPos+1];
                    nFindPos = fontName.rfind(".");
                    fontName = fontName.substr(0, nFindPos);
                }
            }

            int flags = 0;
            if (textDefinition._alignment == TextHAlignment::CENTER) {
                flags |= Qt::AlignHCenter;
            }
            else if (textDefinition._alignment == TextHAlignment::LEFT) {
                flags |= Qt::AlignLeft;
            }
            else if (textDefinition._alignment == TextHAlignment::RIGHT) {
                flags |= Qt::AlignRight;
            }

            if (textDefinition._vertAlignment == TextVAlignment::TOP) {
                flags |= Qt::AlignTop;
            }
            else if (textDefinition._vertAlignment == TextVAlignment::BOTTOM) {
                flags |= Qt::AlignBottom;
            }
            else if (textDefinition._vertAlignment == TextVAlignment::CENTER) {
                flags |= Qt::AlignVCenter;
            }

            QRect rect;
            QFont font(fontName.c_str(), fontSize);
            QImage* image = new QImage(100, 100, QImage::Format_ARGB32);
            QPainter painter(image);
            painter.setFont(font);
            rect = painter.boundingRect(rect, flags, pszText);

            // if content width is 0, use text size as content size
            if (size.width() <= 0)
            {
                size.setWidth(rect.width());
                size.setHeight(rect.height());
            }

            QRect drawRect(0, 0, 0, 0);
            drawRect.setRight(rect.width());
            drawRect.setBottom(rect.height());

            m_pImage = new QImage(size, QImage::Format_ARGB32);
            m_pPainter = new QPainter(m_pImage);

            m_pPainter->setCompositionMode(QPainter::CompositionMode_Source);
            m_pPainter->fillRect(drawRect, Qt::transparent);
            m_pPainter->setCompositionMode(QPainter::CompositionMode_SourceOver);

            m_pPainter->setPen(Qt::white);
            m_pPainter->setFont(font);
            m_pPainter->drawText(drawRect, flags, pszText);
            m_pPainter->end();

//            CC_SAFE_DELETE(m_pPainter);

            nRet = true;
        } while (0);
        return nRet;
    }
Example #17
0
/*!
  \brief Draw the marker
  \param p Painter
  \param x X position
  \param y Y position
  \param r Bounding rectangle
*/
void QwtMarker::draw(QPainter *p, int x, int y, const QRect &r)
{
    // draw lines
    if (d_style != NoLine)
    {
        p->setPen(d_pen);
        if ((d_style == HLine) || (d_style == Cross))
            p->drawLine(r.left(), y, r.right(), y);
        if ((d_style == VLine)||(d_style == Cross))
            p->drawLine(x, r.top(), x, r.bottom());
    }

    // draw symbol
    QSize sSym;
    if (d_sym.style() != QwtSymbol::None)
    {
        sSym = d_sym.size();
        d_sym.draw(p, x - (sSym.width() - 1) / 2 ,y - (sSym.width() - 1) / 2);
    }
    else
    {
        sSym.setWidth(0);
        sSym.setHeight(0);
    }
    

    // draw label
    if (!d_label.isEmpty())
    {
        p->setPen(d_tPen);
        p->setFont(d_font);

        const int th = p->fontMetrics().height();
        const int tw = p->fontMetrics().width(d_label);
        int lw = qwtMax(int(d_pen.width()), 1);
        int lw1;

        if ((d_style == VLine) || (d_style == HLine))
        {
            lw1 = (lw + 1) / 2 + LabelDist;
            lw = lw / 2 + LabelDist;
        }
        else 
        {
            lw1 = qwtMax((lw + 1) / 2, (sSym.width() + 1) / 2) + LabelDist;
            lw = qwtMax(lw / 2, (sSym.width() + 1) / 2) + LabelDist;
        }

        
        QRect tr;
        if (d_style == VLine)
        {
            if (d_align & (int) Qt::AlignTop)
               tr.setY(r.top() + LabelDist);
            else if (d_align & (int) Qt::AlignBottom)
               tr.setY(r.bottom() - LabelDist - th);
            else
               tr.setY(r.top() + (r.bottom() - r.top()) / 2);
        }
        else 
        {
            if (d_align & (int) Qt::AlignTop)
               tr.setY(y - lw - th);
            else if (d_align & (int) Qt::AlignBottom)
               tr.setY(y + lw1);
            else
               tr.setY(y - th/2);
        }


        if (d_style == HLine)
        {
            if (d_align & (int) Qt::AlignLeft)
               tr.setX(r.left() + LabelDist);
            else if (d_align & (int) Qt::AlignRight)
               tr.setX(r.right() - tw - LabelDist);
            else
               tr.setX(r.left() + (r.right() - r.left()) / 2);
        }
        else
        {
            if (d_align & (int) Qt::AlignLeft)
               tr.setX(x - tw - lw);
            else if (d_align & (int) Qt::AlignRight)
               tr.setX(x + lw1);
            else
               tr.setX(x - tw/ 2);
        }

        tr.setHeight(th);
        tr.setWidth(tw);    

        p->drawText(tr, Qt::AlignTop|Qt::AlignHCenter, d_label); 
    }
}
Example #18
0
    /* Fully working, now displays last row and column correctly */
void PixelGrid::resizeEvent(QResizeEvent* event) {
    QSize* evtSize = new QSize(event->size()/(PIXEL_S));
    evtSize->setWidth((event->size().width()-PIXEL_S)/PIXEL_S);
    evtSize->setHeight((event->size().height()-PIXEL_S)/PIXEL_S);
    emit resized(*evtSize);
}
Example #19
0
void QtCalculator::updateGeometry()
{
    QObjectList *l;
    QSize s;
    int margin;

    //
    // Uppermost bar
    //
    calc_display->setMinimumWidth(calc_display->fontMetrics().maxWidth() * 15);

    //
    // Button groups (base and angle)
    //
    //QButtonGroup *g;
    //g = (QButtonGroup*)(anglebutton[0]->parentWidget());
    //g = (QButtonGroup*)(basebutton[0]->parentWidget());

    //
    // Calculator buttons
    //
    s.setWidth(mSmallPage->fontMetrics().width("MMM"));
    s.setHeight(mSmallPage->fontMetrics().lineSpacing());

    l = (QObjectList*)mSmallPage->children(); // silence please

    for(uint i=0; i < l->count(); i++)
    {
        QObject *o = l->at(i);
        if( o->isWidgetType() )
        {
            margin = QApplication::style().
                pixelMetric(QStyle::PM_ButtonMargin, ((QWidget *)o))*2;
            ((QWidget*)o)->setMinimumSize(s.width()+margin, s.height()+margin);
            ((QWidget*)o)->installEventFilter( this );
            ((QWidget*)o)->setAcceptDrops(true);
        }
    }

    l = (QObjectList*)mLargePage->children(); // silence please

    int h1 = pbF->minimumSize().height();
    int h2 = (int)((((float)h1 + 4.0) / 5.0));
    s.setWidth(mLargePage->fontMetrics().width("MMM") +
               QApplication::style().
               pixelMetric(QStyle::PM_ButtonMargin, pbF)*2);
    s.setHeight(h1 + h2);

    for(uint i = 0; i < l->count(); i++)
    {
        QObject *o = l->at(i);
        if(o->isWidgetType())
        {
            ((QWidget*)o)->setFixedSize(s);
            ((QWidget*)o)->installEventFilter(this);
            ((QWidget*)o)->setAcceptDrops(true);
        }
    }

    //
    // The status bar
    //
    s.setWidth( statusINVLabel->fontMetrics().width("NORM") +
                statusINVLabel->frameWidth() * 2 + 10);
    statusINVLabel->setMinimumWidth(s.width());
    statusHYPLabel->setMinimumWidth(s.width());

    //setFixedSize(minimumSize());
}
Example #20
0
void QgsCredentialDialog::requestCredentialsMasterPassword( QString * password, bool stored , bool *ok )
{
  QgsDebugMsg( "Entering." );
  stackedWidget->setCurrentIndex( 1 );

  QString titletxt( stored ? tr( "Enter CURRENT master authentication password" ) : tr( "Set NEW master authentication password" ) );
  lblPasswordTitle->setText( titletxt );

  leMasterPassVerify->setVisible( !stored );
  lblDontForget->setVisible( !stored );

  QApplication::setOverrideCursor( Qt::ArrowCursor );

  grpbxPassAttempts->setVisible( false );
  int passfailed = 0;
  while ( true )
  {
    mOkButton->setEnabled( false );
    // TODO: have the number of attempted passwords configurable in auth settings?
    if ( passfailed >= 3 )
    {
      lblSavedForSession->setVisible( false );
      grpbxPassAttempts->setTitle( tr( "Password attempts: %1" ).arg( passfailed ) );
      grpbxPassAttempts->setVisible( true );
    }

    // resize vertically to fit contents
    QSize s = sizeHint();
    s.setWidth( width() );
    resize( s );

    QgsDebugMsg( "exec()" );
    *ok = exec() == QDialog::Accepted;
    QgsDebugMsg( QString( "exec(): %1" ).arg( *ok ? "true" : "false" ) );

    if ( *ok )
    {
      bool passok = !leMasterPass->text().isEmpty();
      if ( passok && stored && !chkbxEraseAuthDb->isChecked() )
      {
        passok = QgsAuthManager::instance()->verifyMasterPassword( leMasterPass->text() );
      }

      if ( passok && !stored )
      {
        passok = ( leMasterPass->text() == leMasterPassVerify->text() );
      }

      if ( passok || chkbxEraseAuthDb->isChecked() )
      {
        if ( stored && chkbxEraseAuthDb->isChecked() )
        {
          QgsAuthManager::instance()->setScheduledAuthDbErase( true );
        }
        else
        {
          *password = leMasterPass->text();
        }
        break;
      }
      else
      {
        if ( stored )
          ++passfailed;

        leMasterPass->setStyleSheet( invalidStyle_() );
        if ( leMasterPassVerify->isVisible() )
        {
          leMasterPassVerify->setStyleSheet( invalidStyle_() );
        }
      }
    }
    else
    {
      break;
    }

    if ( passfailed >= 5 )
    {
      break;
    }
  }

  // don't leave master password in singleton's text field, or the ability to show it
  leMasterPass->clear();
  chkMasterPassShow->setChecked( false );
  leMasterPassVerify->clear();

  chkbxEraseAuthDb->setChecked( false );
  lblSavedForSession->setVisible( true );

  // re-enable OK button or non-master-password requests will be blocked
  // needs to come after leMasterPass->clear() or textChanged auto-slot with disable it again
  mOkButton->setEnabled( true );

  QApplication::restoreOverrideCursor();

  if ( passfailed >= 5 )
  {
    close();
  }
}
Example #21
0
void Size::setWidth(int width)
{
	QSize s = value().toSize();
	s.setWidth(width);
	setValue(s);
}
QSize PageSelectWidgetItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QSize size = QStyledItemDelegate::sizeHint(option, index);
    size.setWidth(mView->viewport()->width());
    return size;
}
QSize RatingItemDelegate::sizeHint(const QStyleOptionViewItem& option,
                                   const QModelIndex& index) const {
  QSize size = PlaylistDelegateBase::sizeHint(option, index);
  size.setWidth(size.height() * RatingPainter::kStarCount);
  return size;
}
Example #24
0
void QTodoList::fixItemSize(QTodoItem* item)
{
	QSize s = item->sizeHint();
	s.setWidth(vbox->width()-vbox->margin()*2);
	item->resize(s);
}
Example #25
0
void ExportAsImageDialog::accept()
{
    const QString fileName = mUi->fileNameEdit->text();
    if (fileName.isEmpty())
        return;

    if (QFile::exists(fileName)) {
        const QMessageBox::StandardButton button =
                QMessageBox::warning(this,
                                     tr("Export as Image"),
                                     tr("%1 already exists.\n"
                                        "Do you want to replace it?")
                                     .arg(QFileInfo(fileName).fileName()),
                                     QMessageBox::Yes | QMessageBox::No,
                                     QMessageBox::No);

        if (button != QMessageBox::Yes)
            return;
    }

    const bool visibleLayersOnly = mUi->visibleLayersOnly->isChecked();
    const bool useCurrentScale = mUi->currentZoomLevel->isChecked();
    const bool drawTileGrid = mUi->drawTileGrid->isChecked();
    const bool includeBackgroundColor = mUi->includeBackgroundColor->isChecked();

    MapRenderer *renderer = mMapDocument->renderer();

    // Remember the current render flags
    const Tiled::RenderFlags renderFlags = renderer->flags();

    renderer->setFlag(ShowTileObjectOutlines, false);

    QSize mapSize = renderer->mapSize();

    QMargins margins = mMapDocument->map()->computeLayerOffsetMargins();
    mapSize.setWidth(mapSize.width() + margins.left() + margins.right());
    mapSize.setHeight(mapSize.height() + margins.top() + margins.bottom());

    if (useCurrentScale)
        mapSize *= mCurrentScale;

    QImage image;

    try {
        image = QImage(mapSize, QImage::Format_ARGB32_Premultiplied);

        if (includeBackgroundColor) {
            if (mMapDocument->map()->backgroundColor().isValid())
                image.fill(mMapDocument->map()->backgroundColor());
            else
                image.fill(Qt::gray);
        } else {
            image.fill(Qt::transparent);
        }
    } catch (const std::bad_alloc &) {
        QMessageBox::critical(this,
                              tr("Out of Memory"),
                              tr("Could not allocate sufficient memory for the image. "
                                 "Try reducing the zoom level or using a 64-bit version of Tiled."));
        return;
    }

    if (image.isNull()) {
        const size_t gigabyte = 1073741824;
        const size_t memory = size_t(mapSize.width()) * size_t(mapSize.height()) * 4;
        const double gigabytes = (double) memory / gigabyte;

        QMessageBox::critical(this,
                              tr("Image too Big"),
                              tr("The resulting image would be %1 x %2 pixels and take %3 GB of memory. "
                                 "Tiled is unable to create such an image. Try reducing the zoom level.")
                              .arg(mapSize.width())
                              .arg(mapSize.height())
                              .arg(gigabytes, 0, 'f', 2));
        return;
    }

    QPainter painter(&image);

    if (useCurrentScale) {
        if (smoothTransform(mCurrentScale))
            painter.setRenderHints(QPainter::SmoothPixmapTransform);

        painter.setTransform(QTransform::fromScale(mCurrentScale,
                                                   mCurrentScale));
        renderer->setPainterScale(mCurrentScale);
    } else {
        renderer->setPainterScale(1);
    }

    painter.translate(margins.left(), margins.top());

    foreach (const Layer *layer, mMapDocument->map()->layers()) {
        if (visibleLayersOnly && !layer->isVisible())
            continue;

        painter.setOpacity(layer->opacity());
        painter.translate(layer->offset());

        const TileLayer *tileLayer = dynamic_cast<const TileLayer*>(layer);
        const ObjectGroup *objGroup = dynamic_cast<const ObjectGroup*>(layer);
        const ImageLayer *imageLayer = dynamic_cast<const ImageLayer*>(layer);

        if (tileLayer) {
            renderer->drawTileLayer(&painter, tileLayer);
        } else if (objGroup) {
            QList<MapObject*> objects = objGroup->objects();

            if (objGroup->drawOrder() == ObjectGroup::TopDownOrder)
                qStableSort(objects.begin(), objects.end(), objectLessThan);

            foreach (const MapObject *object, objects) {
                if (object->isVisible()) {
                    if (object->rotation() != qreal(0)) {
                        QPointF origin = renderer->pixelToScreenCoords(object->position());
                        painter.save();
                        painter.translate(origin);
                        painter.rotate(object->rotation());
                        painter.translate(-origin);
                    }

                    const QColor color = MapObjectItem::objectColor(object);
                    renderer->drawMapObject(&painter, object, color);

                    if (object->rotation() != qreal(0))
                        painter.restore();
                }
            }
        } else if (imageLayer) {
            renderer->drawImageLayer(&painter, imageLayer);
        }

        painter.translate(-layer->offset());
    }
/*!
  \brief Draw the raster data
  \param painter Painter
  \param xMap X-Scale Map
  \param yMap Y-Scale Map
  \param canvasRect Contents rectangle of the plot canvas
*/
void QwtPlotRasterItem::draw( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect ) const
{
    if ( canvasRect.isEmpty() || d_data->alpha == 0 )
        return;

    const bool doCache = qwtUseCache( d_data->cache.policy, painter );

    const QwtInterval xInterval = interval( Qt::XAxis );
    const QwtInterval yInterval = interval( Qt::YAxis );

    /*
        Scaling an image always results in a loss of
        precision/quality. So we always render the image in
        paint device resolution.
    */

    QwtScaleMap xxMap, yyMap;
    qwtTransformMaps( painter->transform(), xMap, yMap, xxMap, yyMap );

    QRectF paintRect = painter->transform().mapRect( canvasRect );
    QRectF area = QwtScaleMap::invTransform( xxMap, yyMap, paintRect );

    const QRectF br = boundingRect();
    if ( br.isValid() && !br.contains( area ) )
    {
        area &= br;
        if ( !area.isValid() )
            return;

        paintRect = QwtScaleMap::transform( xxMap, yyMap, area );
    }

    QRectF imageRect;
    QImage image;

    QRectF pixelRect = pixelHint(area);
    if ( !pixelRect.isEmpty() )
    {
        // pixel in target device resolution 
        const double dx = qAbs( xxMap.invTransform( 1 ) - xxMap.invTransform( 0 ) );
        const double dy = qAbs( yyMap.invTransform( 1 ) - yyMap.invTransform( 0 ) );

        if ( dx > pixelRect.width() && dy > pixelRect.height() )
        {
            /*
              When the resolution of the data pixels is higher than
              the resolution of the target device we render in
              target device resolution.
             */
            pixelRect = QRectF();
        }
    }

    if ( pixelRect.isEmpty() )
    {
        if ( QwtPainter::roundingAlignment( painter ) )
        {
            // we want to have maps, where the boundaries of
            // the aligned paint rectangle exactly match the area

            paintRect = qwtAlignRect(paintRect);
            qwtAdjustMaps(xxMap, yyMap, area, paintRect);
        }

        // When we have no information about position and size of
        // data pixels we render in resolution of the paint device.

        image = compose(xxMap, yyMap, 
            area, paintRect, paintRect.size().toSize(), doCache);
        if ( image.isNull() )
            return;

        // Remove pixels at the boundaries, when explicitly
        // excluded in the intervals

        imageRect = qwtStripRect(paintRect, area, 
            xxMap, yyMap, xInterval, yInterval);

        if ( imageRect != paintRect )
        {
            const QRect r( 
                qRound( imageRect.x() - paintRect.x()),
                qRound( imageRect.y() - paintRect.y() ),
                qRound( imageRect.width() ),
                qRound( imageRect.height() ) );
                
            image = image.copy(r);
        }   
    }
    else
    {
        if ( QwtPainter::roundingAlignment( painter ) )
            paintRect = qwtAlignRect(paintRect);

        // align the area to the data pixels
        QRectF imageArea = qwtExpandToPixels(area, pixelRect);

        if ( imageArea.right() == xInterval.maxValue() &&
            !( xInterval.borderFlags() & QwtInterval::ExcludeMaximum ) )
        {
            imageArea.adjust(0, 0, pixelRect.width(), 0);
        }
        if ( imageArea.bottom() == yInterval.maxValue() &&
            !( yInterval.borderFlags() & QwtInterval::ExcludeMaximum ) )
        {
            imageArea.adjust(0, 0, 0, pixelRect.height() );
        }

        QSize imageSize;
        imageSize.setWidth( qRound( imageArea.width() / pixelRect.width() ) );
        imageSize.setHeight( qRound( imageArea.height() / pixelRect.height() ) );
        image = compose(xxMap, yyMap, 
            imageArea, paintRect, imageSize, doCache );
        if ( image.isNull() )
            return;

        imageRect = qwtStripRect(paintRect, area, 
            xxMap, yyMap, xInterval, yInterval);

        if ( ( image.width() > 1 || image.height() > 1 ) &&
            testPaintAttribute( PaintInDeviceResolution ) )
        {
            // Because of rounding errors the pixels 
            // need to be expanded manually to rectangles of 
            // different sizes

            image = qwtExpandImage(image, xxMap, yyMap, 
                imageArea, area, paintRect, xInterval, yInterval );
        }
    }

    painter->save();
    painter->setWorldTransform( QTransform() );
    
    QwtPainter::drawImage( painter, imageRect, image );

    painter->restore();
}
/**
 * The event handler running on the preview generation thread.
 *
 * \param[in] e The received message.  This should be one of the
 * messages GET_PREVIEW, PREVIEW_SUCCESS, or PREVIEW_FAILED.
 *
 * \warning This function should only be called from the preview
 * generation thread.

 * \bug This function appears to incorrectly compute the value of
 * lastBlockTime.  The call to max() will correctly ensure that if the
 * old value of lastBlockTime is zero, that the new time for the first
 * "retry" will be two.  The problem is that all subsequent "retries"
 * will also be limited to two, so there is no increasing back off
 * interval like it appears was intended.
 */
bool PreviewGeneratorQueue::event(QEvent *e)
{
    if (e->type() != MythEvent::MythEventMessage)
        return QObject::event(e);

    MythEvent *me = static_cast<MythEvent*>(e);
    if (me->Message() == "GET_PREVIEW")
    {
        const QStringList &list = me->ExtraDataList();
        QStringList::const_iterator it = list.begin();
        ProgramInfo evinfo(it, list.end());
        QString token;
        QSize outputsize;
        QString outputfile;
        long long time = -1LL;
        if (it != list.end())
            token = (*it++);
        if (it != list.end())
            outputsize.setWidth((*it++).toInt());
        if (it != list.end())
            outputsize.setHeight((*it++).toInt());
        if (it != list.end())
            outputfile = (*it++);
        if (it != list.end())
            time = (*it++).toLongLong();
        QString fn;
        if (it != list.end())
        {
            bool time_fmt_sec = (*it++).toInt() != 0;
            fn = GeneratePreviewImage(evinfo, outputsize, outputfile,
                                      time, time_fmt_sec, token);
        }
        return true;
    }
    else if (me->Message() == "PREVIEW_SUCCESS" ||
             me->Message() == "PREVIEW_FAILED")
    {
        uint recordedingID = me->ExtraData(0).toUInt(); // pginfo->GetRecordingID()
        QString filename   = me->ExtraData(1); // outFileName
        QString msg        = me->ExtraData(2);
        QString datetime   = me->ExtraData(3);
        QString token      = me->ExtraData(4);

        {
            QMutexLocker locker(&m_lock);
            QMap<QString,QString>::iterator kit = m_tokenToKeyMap.find(token);
            if (kit == m_tokenToKeyMap.end())
            {
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    QString("Failed to find token %1 in map.").arg(token));
                return true;
            }
            PreviewMap::iterator it = m_previewMap.find(*kit);
            if (it == m_previewMap.end())
            {
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    QString("Failed to find key %1 in map.").arg(*kit));
                return true;
            }

            if ((*it).gen)
                (*it).gen->deleteLater();
            (*it).gen           = nullptr;
            (*it).genStarted    = false;
            if (me->Message() == "PREVIEW_SUCCESS")
            {
                (*it).attempts      = 0;
                (*it).lastBlockTime = 0;
                (*it).blockRetryUntil = QDateTime();
            }
            else
            {
                (*it).lastBlockTime =
                    max(m_minBlockSeconds, (*it).lastBlockTime * 2);
                (*it).blockRetryUntil =
                    MythDate::current().addSecs((*it).lastBlockTime);
            }

            QStringList list;
            list.push_back(QString::number(recordedingID));
            list.push_back(filename);
            list.push_back(msg);
            list.push_back(datetime);
            QSet<QString>::const_iterator tit = (*it).tokens.begin();
            for (; tit != (*it).tokens.end(); ++tit)
            {
                kit = m_tokenToKeyMap.find(*tit);
                if (kit != m_tokenToKeyMap.end())
                    m_tokenToKeyMap.erase(kit);
                list.push_back(*tit);
            }

            if (list.size() > 4)
            {
                QSet<QObject*>::iterator sit = m_listeners.begin();
                for (; sit != m_listeners.end(); ++sit)
                {
                    MythEvent *e = new MythEvent(me->Message(), list);
                    QCoreApplication::postEvent(*sit, e);
                }
                (*it).tokens.clear();
            }

            m_running = (m_running > 0) ? m_running - 1 : 0;
        }

        UpdatePreviewGeneratorThreads();

        return true;
    }
    return false;
}
Example #28
0
void TopBar::resizeEvent(QGraphicsSceneResizeEvent* /*event*/)
{
    //Check orientation
    QString topbarName;
    QSize mainViewSize = m_mainView->size();
    int rotationAngle = static_cast<MainView*>(m_mainView)->rotationAngle();
    if(rotationAngle == 90 || rotationAngle == 270 ) {
       int wd = mainViewSize.width();
       int ht = mainViewSize.height();
       mainViewSize.setWidth(ht);
       mainViewSize.setHeight(wd);
    }
    bool m_orientationChanged = false;
    if(mainViewSize.height() >= mainViewSize.width()) {
        if(m_orientation == TopBar::Landscape)
            m_orientationChanged = true;
        m_orientation = TopBar::Portrait;
        topbarName = "topbar.svg";
    }
    else {
        if(m_orientation == TopBar::Portrait)
            m_orientationChanged = true;
        m_orientation = TopBar::Landscape;
        topbarName = "topbar_horisontal.svg";
    }

    //Calculate new size, resize by height, don't make it wider than the screen
    QHash<QString, QSize>sizes = (Theme::p()->theme() == Theme::Blue) ?
        m_sizesBlue : m_sizesLime;

    //Get current size for topbarpixmap
    QSize currentSize = !m_topBarPixmap.isNull() && !m_orientationChanged ?
            m_topBarPixmap.size() : sizes[topbarName];
    QSize newSize = !m_orientationChanged ? QSize(currentSize) : sizes[topbarName];

    //Scale according to aspect ratio
    newSize.scale(size().toSize(), Qt::KeepAspectRatio);

    //fix width to window widht if previous scaling produced too narrow image
    if(newSize.width() < size().width()) {
        newSize.scale(size().toSize(), Qt::KeepAspectRatioByExpanding);
    }

    //Calculate scaling factor for rest of the graphics scaling
    qreal scaleFactor = (newSize.width() *1.0) / (currentSize.width() * 1.0);

    //Scale graphics, if the scalefactor applies
    //This is really heavy since the SVG graphics are read again from the resource
    if(scaleFactor != 1 || m_topBarPixmap.isNull() )  {
        m_topBarPixmap = Theme::p()->pixmap(topbarName, newSize );
        m_topBarUserIcon = Theme::p()->pixmap("user_default_icon.svg",
                !m_topBarUserIcon.isNull() && !m_orientationChanged ? m_topBarUserIcon.size()* scaleFactor : sizes["user_default_icon.svg"] * scaleFactor);

        m_topBarUserStatus = Theme::p()->pixmap("user_status_online.svg",
                !m_topBarUserStatus.isNull() && !m_orientationChanged ? m_topBarUserStatus.size() * scaleFactor : sizes["user_status_online.svg"] * scaleFactor);

        m_topBarStatusBarLeft = Theme::p()->pixmap("status_field_left.svg",
                !m_topBarStatusBarLeft.isNull() && !m_orientationChanged ? m_topBarStatusBarLeft.size()* scaleFactor : sizes["status_field_left.svg"] * scaleFactor);

        m_topBarStatusBarRight = Theme::p()->pixmap("status_field_right.svg",
                !m_topBarStatusBarRight.isNull() && !m_orientationChanged ? m_topBarStatusBarRight.size()* scaleFactor : sizes["status_field_right.svg"] * scaleFactor);

        m_topBarStatusBarMiddle = Theme::p()->pixmap("status_field_middle.svg",
                !m_topBarStatusBarMiddle.isNull() && !m_orientationChanged ? m_topBarStatusBarMiddle.size() * scaleFactor : QSize(185, sizes["status_field_middle.svg"].height()) * scaleFactor);

        //Update the sizeHint to match the size of the scaled m_topBarPixmap
        updateGeometry();

        //Point Update - Positions relative to the Top Bar "Backgroud" size.
        //TODO: consider some layout instead of calculating relative locations
        QSize topBarPixmapSize = m_topBarPixmap.size();
        QSize topBarUserIconSize = m_topBarUserIcon.size();
        QSize topBarUserStatusSize = m_topBarUserStatus.size();
        QSize topBarStatusBarLeftSize = m_topBarStatusBarLeft.size();
        QSize topBarStatusBarMiddleSize = m_topBarStatusBarMiddle.size();

        //Location for Title text 5% width, 35% height of the background pixmap
        m_topBarTitlePoint = QPoint(topBarPixmapSize.width()* 0.05,
                topBarPixmapSize.height() * 0.35);

        //User Icon location
        //Placing 70% of the width and 10% of the height of the top bar background
        m_topBarUserIconPoint = QPoint((topBarPixmapSize.width() * 0.7), (topBarPixmapSize.height() * 0.1));

        //If Blue theme is in use - position user status icon on the right side of the user icon
        if(!m_isLimeTheme) {
            //Place the status icon on top of the right edge of the user icon, lower it by 35% of the height of the user icon
            m_topBarUserStatusPoint = QPoint( ( (m_topBarUserIconPoint.x()+topBarUserIconSize.width() ) -
                    ( topBarUserStatusSize.width()/2 )),
                (m_topBarUserIconPoint.y() + (topBarUserIconSize.height() * 0.35 )));
        }
        //If Lime theme is in use - position user status icon on the left side of the user icon
        else {
            //Place the status icon on top of the left side of the user icon, lower it by 50% of the height of the user icon
            //and move left by 5% of the icon
            m_topBarUserStatusPoint = QPoint(  m_topBarUserIconPoint.x() + ( topBarUserIconSize.width() * 0.05),
                        (m_topBarUserIconPoint.y() + (topBarUserIconSize.height() * 0.5 )));
        }

        //Status bar
        //Placing the left side of the status bar  5% of the width, 50% of the height of the top bar background
        //Set the text baseline 80% of the height of the status bar
        m_topBarStatusBarLeftPoint = QPoint( (topBarPixmapSize.width()* 0.05),
                                                        (topBarPixmapSize.height() * 0.5));
        m_topBarStatusBarMiddlePoint = QPoint( (m_topBarStatusBarLeftPoint.x() + topBarStatusBarLeftSize.width()),
                                                            (m_topBarStatusBarLeftPoint.y()));
        m_topBarStatusBarRightPoint = QPoint( (m_topBarStatusBarMiddlePoint.x() + topBarStatusBarMiddleSize.width()),
                                                        (m_topBarStatusBarMiddlePoint.y() ) );
        m_topBarStatusBarTextPoint = QPoint(m_topBarStatusBarMiddlePoint.x(),
                                                        m_topBarStatusBarMiddlePoint.y() + (topBarStatusBarMiddleSize.height()*0.8) );
    } //if scalefactor
}
Example #29
0
QSize TabBar::tabSizeHint(int index) const
{
    if (!isVisible()) {
        // Don't calculate it when tabbar is not visible
        // It produces invalid size anyway
        return QSize(-1, -1);
    }

    static int PINNED_TAB_WIDTH = -1;
    static int MINIMUM_ACTIVE_TAB_WIDTH = -1;

    if (PINNED_TAB_WIDTH == -1) {
        PINNED_TAB_WIDTH = 16 + style()->pixelMetric(QStyle::PM_TabBarTabHSpace, 0, this);
        MINIMUM_ACTIVE_TAB_WIDTH = PINNED_TAB_WIDTH + style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, this);
        // just a hack: we want to be sure buttonAddTab and buttonListTabs can't cover the active tab
        MINIMUM_ACTIVE_TAB_WIDTH = qMax(MINIMUM_ACTIVE_TAB_WIDTH, 6 + m_tabWidget->buttonListTabs()->width() + m_tabWidget->buttonAddTab()->width());
    }

    QSize size = QTabBar::tabSizeHint(index);
    WebTab* webTab = qobject_cast<WebTab*>(m_tabWidget->widget(index));
    TabBar* tabBar = const_cast <TabBar*>(this);
    bool adjustingActiveTab = false;

    if (webTab && webTab->isPinned()) {
        size.setWidth(PINNED_TAB_WIDTH);
    }
    else {
        int availableWidth = width() - (PINNED_TAB_WIDTH * m_pinnedTabsCount) - m_tabWidget->buttonListTabs()->width() - m_tabWidget->buttonAddTab()->width();
        int normalTabsCount = count() - m_pinnedTabsCount;
        if (availableWidth >= MAXIMUM_TAB_WIDTH * normalTabsCount) {
            m_normalTabWidth = MAXIMUM_TAB_WIDTH;
            size.setWidth(m_normalTabWidth);
        }
        else if (availableWidth < MINIMUM_TAB_WIDTH * normalTabsCount) {
            // Tabs don't fit at all in tabbar even with MINIMUM_TAB_WIDTH
            // We will try to use as low width of tabs as possible
            // to try avoid overflowing tabs into tabbar buttons

            int maxWidthForTab = availableWidth / normalTabsCount;
            m_activeTabWidth = maxWidthForTab;
            if (m_activeTabWidth < MINIMUM_ACTIVE_TAB_WIDTH) {
                maxWidthForTab = (availableWidth - MINIMUM_ACTIVE_TAB_WIDTH) / (normalTabsCount - 1);
                m_activeTabWidth = MINIMUM_ACTIVE_TAB_WIDTH;
                adjustingActiveTab = true;
            }

            if (maxWidthForTab < PINNED_TAB_WIDTH) {
                // FIXME: It overflows now

                m_normalTabWidth = PINNED_TAB_WIDTH;
                if (index == currentIndex()) {
                    size.setWidth(m_activeTabWidth);
                }
                else {
                    size.setWidth(m_normalTabWidth);
                }
            }
            else {
                m_normalTabWidth = maxWidthForTab;

                // Fill any empty space (we've got from rounding) with active tab
                if (index == currentIndex()) {
                    if (adjustingActiveTab) {
                        m_activeTabWidth = (availableWidth - MINIMUM_ACTIVE_TAB_WIDTH
                                            - maxWidthForTab * (normalTabsCount - 1)) + m_activeTabWidth;
                    }
                    else {
                        m_activeTabWidth = (availableWidth - maxWidthForTab * normalTabsCount) + maxWidthForTab;
                    }
                    adjustingActiveTab = true;
                    size.setWidth(m_activeTabWidth);
                }
                else {
                    size.setWidth(m_normalTabWidth);
                }

                if (tabsClosable()) {
                    // Hiding close buttons to save some space
                    tabBar->setTabsClosable(false);

                    tabBar->showCloseButton(currentIndex());
                }
            }
        }
        else {
            int maxWidthForTab = availableWidth / normalTabsCount;
            m_activeTabWidth = maxWidthForTab;
            if (m_activeTabWidth < MINIMUM_ACTIVE_TAB_WIDTH) {
                maxWidthForTab = (availableWidth - MINIMUM_ACTIVE_TAB_WIDTH) / (normalTabsCount - 1);
                m_activeTabWidth = MINIMUM_ACTIVE_TAB_WIDTH;
                adjustingActiveTab = true;
            }
            m_normalTabWidth = maxWidthForTab;

            // Fill any empty space (we've got from rounding) with active tab
            if (index == currentIndex()) {
                if (adjustingActiveTab) {
                    m_activeTabWidth = (availableWidth - MINIMUM_ACTIVE_TAB_WIDTH
                                        - maxWidthForTab * (normalTabsCount - 1)) + m_activeTabWidth;
                }
                else {
                    m_activeTabWidth = (availableWidth - maxWidthForTab * normalTabsCount) + maxWidthForTab;
                }
                adjustingActiveTab = true;
                size.setWidth(m_activeTabWidth);
            }
            else {
                size.setWidth(m_normalTabWidth);
            }

            // Restore close buttons according to preferences
            if (!tabsClosable()) {
                tabBar->setTabsClosable(true);

                // Hide close buttons on pinned tabs
                for (int i = 0; i < count(); ++i) {
                    tabBar->updatePinnedTabCloseButton(i);
                }
            }
        }
    }

    if (index == currentIndex()) {
        int xForAddTabButton = (PINNED_TAB_WIDTH * m_pinnedTabsCount) + (count() - m_pinnedTabsCount) * (m_normalTabWidth);
        if (adjustingActiveTab) {
            xForAddTabButton += m_activeTabWidth - m_normalTabWidth;
        }

        // RTL Support
        if (QApplication::layoutDirection() == Qt::RightToLeft) {
            xForAddTabButton = width() - xForAddTabButton;
        }
        emit tabBar->moveAddTabButton(xForAddTabButton);
    }

    return size;
}
Example #30
0
QSize KeyEditor::sizeHint() const {
	QSize hint = QLineEdit::sizeHint();
	QFontMetrics fm(font());
	hint.setWidth(fm.height() * 4);
	return hint;
}