Example #1
0
QTreeWidgetItemIterator::QTreeWidgetItemIterator(QTreeWidgetItem *item, IteratorFlags flags)
    : d_ptr(new QTreeWidgetItemIteratorPrivate(
                this, qobject_cast<QTreeModel*>(item->view->model()))),
      current(item), flags(flags)
{
    Q_D(QTreeWidgetItemIterator);
    Q_ASSERT(item);
    QTreeModel *model = qobject_cast<QTreeModel*>(item->view->model());
    Q_ASSERT(model);
    model->iterators.append(this);

    // Initialize m_currentIndex and m_parentIndex as it would be if we had traversed from
    // the beginning.
    QTreeWidgetItem *parent = item;
    parent = parent->parent();
    QList<QTreeWidgetItem *> children = parent ? parent->children : d->m_model->rootItem->children;
    d->m_currentIndex = children.indexOf(item);

    while (parent) {
        QTreeWidgetItem *itm = parent;
        parent = parent->parent();
        QList<QTreeWidgetItem *> children = parent ? parent->children : d->m_model->rootItem->children;
        int index = children.indexOf(itm);
        d->m_parentIndex.prepend(index);
    }

    if (current && !matchesFlags(current))
        ++(*this);
}
Example #2
0
bool ArtworkLayerSortingModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
    KShape * leftShape = static_cast<KShape*>(left.internalPointer());
    KShape * rightShape = static_cast<KShape*>(right.internalPointer());

    if (! leftShape || ! rightShape)
        return false;

    if (m_document) {
        KShapeLayer * leftLayer = dynamic_cast<KShapeLayer*>(leftShape);
        KShapeLayer * rightLayer = dynamic_cast<KShapeLayer*>(rightShape);
        if (leftLayer && rightLayer) {
            return m_document->layerPos(leftLayer) < m_document->layerPos(rightLayer);
        } else {
            if (leftShape->zIndex() == rightShape->zIndex()) {
                KShapeContainer * leftParent = leftShape->parent();
                KShapeContainer * rightParent = rightShape->parent();
                if (leftParent && leftParent == rightParent) {
                    QList<KShape*> children = leftParent->shapes();
                    return children.indexOf(leftShape) < children.indexOf(rightShape);
                } else {
                    return leftShape < rightShape;
                }
            } else {
                return leftShape->zIndex() < rightShape->zIndex();
            }
        }
    } else {
        if (leftShape->zIndex() == rightShape->zIndex())
            return leftShape < rightShape;
        else
            return leftShape->zIndex() < rightShape->zIndex();
    }
}
Example #3
0
void XSqlQuery::removeErrorListener(XSqlQueryErrorListener* listener)
{
  int i = _errorListeners.indexOf(listener);
  while(-1 != i)
  {
    _errorListeners.removeAt(i);
    i = _errorListeners.indexOf(listener);
  }
}
Example #4
0
void MiaImageForestingTransform::createValidatedSeedPoints(const QList<MiaMarker *> markerList, std::list<PathNode> &outlist)
{
    outlist.clear();
    int width, height, depth;
    width = inputImage->getWidth();
    height = inputImage->getHeight();
    depth = inputImage->getDepth();
    sliceSize = width*height;
    QList<QColor> colorList;
    for( int i = 0; i < markerList.size(); i++ )
    {
        if(markerList.at(i)->getKeyPointNumber()>1)
            continue;
        MiaPoint4D pt = markerList.at(i)->getKeyPointAt(0);
        pt = inputImage->convertPatientCoordinateToVoxel(pt);
        int x,y,z;
        x = pt.pos[0]; y = pt.pos[1]; z = pt.pos[2];
        if(x<0 || x>=width || y<0 || y>=height || z<0 || z>=depth)
            continue;
        int ind = z*sliceSize + y*width + x;

        QColor color = markerList.at(i)->color;
        if(!colorList.contains(color))
        {
            colorList.append(color);
        }
        int colortag = colorList.indexOf(color) + 1;
        PathNode node;
        node.index = ind;
        node.cost = colortag;
        outlist.push_back(node);
    }
}
Example #5
0
Note* Score::upAlt(Element* element)
{
    Element* re = 0;
    if (element->type() == Element::REST) {
        if (_is.track() <= 0)
            return 0;
        _is.setTrack(_is.track() - 1);
        re = searchNote(static_cast<Rest*>(element)->tick(), _is.track());
    }
    else if (element->type() == Element::NOTE) {
        // find segment
        Chord* chord     = static_cast<Note*>(element)->chord();
        Segment* segment = chord->segment();

        // collect all notes for this segment in noteList:
        QList<Note*> rnl;
        int tracks = nstaves() * VOICES;
        for (int track = 0; track < tracks; ++track) {
            Element* el = segment->element(track);
            if (!el || el->type() != Element::CHORD)
                continue;
            rnl.append(static_cast<Chord*>(el)->notes());
            qSort(rnl.begin(), rnl.end(), noteLessThan);
            int idx = rnl.indexOf(static_cast<Note*>(element));
            if (idx < rnl.size()-1)
                ++idx;
            re = rnl.value(idx);
        }
    }
    if (re == 0)
        return 0;
    if (re->type() == Element::CHORD)
        re = ((Chord*)re)->notes().front();
    return (Note*)re;
}
Example #6
0
SettingsDialog::SettingsDialog(Storage* _hardDriveStorage, Storage* _picasaStorage, Storage* _scriptRunner, KinectPluginLoader* _kinectPluginLoader, QWidget *_parent) :
    QDialog(_parent),
    ui(new Ui::SettingsDialog),
    m_kinect(_kinectPluginLoader->plugin()),
    m_hardDriveStorage(_hardDriveStorage),
    m_picasaStorage(_picasaStorage),
    m_scriptRunner(_scriptRunner),
    m_kinectPluginLoader(_kinectPluginLoader),
    m_currentPluginIndex(-1)

{
    BEGIN;
    ui->setupUi(this);

    ui->warning->setVisible(false);
    setAttribute(Qt::WA_DeleteOnClose);

    // hdd storage part
    ui->path->setText(dynamic_cast<HardDriveStorage*>(m_hardDriveStorage->storageImpl())->directoryPath());
    ui->firstImageSpinBox->setValue(m_hardDriveStorage->firstDelay());
    ui->nextImageSpinBox->setValue(m_hardDriveStorage->repeatableDelay());
    ui->storageActive->setCheckState(m_hardDriveStorage->storageActive() ? Qt::Checked : Qt::Unchecked);
    QList<QString> plugins = m_kinectPluginLoader->pluginsList();


    ui->pluginComboBox->insertItems(0, plugins);
    if (plugins.length()) {
	if (m_kinectPluginLoader->plugin()) {
	    m_currentPluginIndex = plugins.indexOf(m_kinectPluginLoader->plugin()->pluginName());
	} else {
	    m_currentPluginIndex = 0;
	}
	ui->pluginComboBox->setCurrentIndex(m_currentPluginIndex);
	connect(ui->pluginComboBox, SIGNAL(currentIndexChanged(int)), SLOT(onKinectPluginChange(int)));
    } else {
// The dtor.
QsciScintillaBase::~QsciScintillaBase()
{
    // Remove it from the pool.
    poolList.removeAt(poolList.indexOf(this));

    delete sci;
}
Example #8
0
int KoLineStyleModel::setLineStyle( Qt::PenStyle style, const QVector<qreal> &dashes )
{
    // check if we select a standard or custom style
    if( style < Qt::CustomDashLine )
    {
        // a standard style
        m_hasTempStyle = false;
        reset();
        return style;
    }
    else if( style == Qt::CustomDashLine )
    {
        // a custom style -> check if already added
        int index = m_styles.indexOf( dashes, Qt::CustomDashLine );
        if( index < 0 )
        {
            // not already added -> add temporarly
            m_tempStyle = dashes;
            m_hasTempStyle = true;
            reset();
            return m_styles.count();
        }
        else
        {
            // already added -> return index
            m_hasTempStyle = false;
            reset();
            return index;
        }
    }
    else
        return -1;
}
Example #9
0
void tst_QScriptEngineDebugger::widget()
{
#if defined(Q_OS_WINCE) && _WIN32_WCE < 0x600
    QSKIP("skipped due to high mem usage until task 261062 is fixed", SkipAll);
#endif

    QScriptEngine engine;
    QScriptEngineDebugger debugger;
    debugger.attachTo(&engine);
    QList<QScriptEngineDebugger::DebuggerWidget> widgets;
    widgets
        << QScriptEngineDebugger::ConsoleWidget
        << QScriptEngineDebugger::StackWidget
        << QScriptEngineDebugger::ScriptsWidget
        << QScriptEngineDebugger::LocalsWidget
        << QScriptEngineDebugger::CodeWidget
        << QScriptEngineDebugger::CodeFinderWidget
        << QScriptEngineDebugger::BreakpointsWidget
        << QScriptEngineDebugger::DebugOutputWidget
        << QScriptEngineDebugger::ErrorLogWidget;
    QList<QWidget*> lst;
    for (int i = 0; i < widgets.size(); ++i) {
        QScriptEngineDebugger::DebuggerWidget dw = widgets.at(i);
        QWidget *wid = debugger.widget(dw);
        QVERIFY(wid != 0);
        QCOMPARE(wid, debugger.widget(dw));
        QVERIFY(lst.indexOf(wid) == -1);
        lst.append(wid);
        QCOMPARE(static_cast<QWidget *>(wid->parent()), (QWidget*)0);
    }
}
Example #10
0
/**
    This returns what next station should be.  This will first check
    if the last station is empty.  If the last station isn't empty then
    this function will return an empty string.
  */
QString cwSurveyChunk::guessLastStationName() const {
    //Need a least two stations for this to work.
    if(stations().size() < 2) {
        return QString();
    }

    if(stations().last().name().isEmpty()) {
        QString stationName;

        if(stations().size() == 2) {
            //Try to get the station name from the previous chunk
            QList<cwSurveyChunk*> chunks = parentTrip()->chunks();
            int index = chunks.indexOf(const_cast<cwSurveyChunk*>(this)) - 1;
            cwSurveyChunk* previousChunk = parentTrip()->chunk(index);
            if(previousChunk != NULL) {
                stationName = previousChunk->stations().last().name();
            }
        }

        if(stationName.isEmpty()) {
            int secondToLastStation = stations().size() - 2;
            stationName = stations().at(secondToLastStation).name();
        }

        QString nextStation = guessNextStation(stationName);
        return nextStation;
    }

    return QString();
}
Example #11
0
static QDomElement _writeOldLegendLayer( QDomDocument &doc, QgsLayerTreeLayer *nodeLayer, bool hasCustomOrder, const QList<QgsMapLayer *> &order )
{
  int drawingOrder = -1;
  if ( hasCustomOrder )
    drawingOrder = order.indexOf( nodeLayer->layer() );

  QDomElement layerElem = doc.createElement( QStringLiteral( "legendlayer" ) );
  layerElem.setAttribute( QStringLiteral( "drawingOrder" ), drawingOrder );
  layerElem.setAttribute( QStringLiteral( "open" ), nodeLayer->isExpanded() ? QStringLiteral( "true" ) : QStringLiteral( "false" ) );
  layerElem.setAttribute( QStringLiteral( "checked" ), QgsLayerTreeUtils::checkStateToXml( nodeLayer->itemVisibilityChecked() ? Qt::Checked : Qt::Unchecked ) );
  layerElem.setAttribute( QStringLiteral( "name" ), nodeLayer->name() );
  layerElem.setAttribute( QStringLiteral( "showFeatureCount" ), nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ) ).toInt() );

  QDomElement fileGroupElem = doc.createElement( QStringLiteral( "filegroup" ) );
  fileGroupElem.setAttribute( QStringLiteral( "open" ), nodeLayer->isExpanded() ? "true" : "false" );
  fileGroupElem.setAttribute( QStringLiteral( "hidden" ), QStringLiteral( "false" ) );

  QDomElement layerFileElem = doc.createElement( QStringLiteral( "legendlayerfile" ) );
  layerFileElem.setAttribute( QStringLiteral( "isInOverview" ), nodeLayer->customProperty( QStringLiteral( "overview" ) ).toInt() );
  layerFileElem.setAttribute( QStringLiteral( "layerid" ), nodeLayer->layerId() );
  layerFileElem.setAttribute( QStringLiteral( "visible" ), nodeLayer->isVisible() ? 1 : 0 );

  layerElem.appendChild( fileGroupElem );
  fileGroupElem.appendChild( layerFileElem );
  return layerElem;
}
KPrConfigureSlideShowDialog::KPrConfigureSlideShowDialog( KPrDocument *document, KPrView *parent )
    : KDialog( parent )
    , m_document( document )
    , m_view(parent)
{
    QWidget *widget = new QWidget( this );

    ui.setupUi( widget );

    ui.slidesComboBox->addItem( i18n( "All slides" ) );
    KPrCustomSlideShows *customSlideShows = document->customSlideShows();
    ui.slidesComboBox->addItems( customSlideShows->names() );

    setMainWidget( widget );

    setCaption( i18n( "Configure Slide Show" ) );

    QString activeCustomSlideShow = document->activeCustomSlideShow();
    if ( activeCustomSlideShow.isEmpty() ) {
        ui.slidesComboBox->setCurrentIndex( 0 );
    }
    else {
        QList<QString> customSlideShows = document->customSlideShows()->names();
        int index = customSlideShows.indexOf( activeCustomSlideShow ) + 1;
        Q_ASSERT( index < ui.slidesComboBox->count() );
        ui.slidesComboBox->setCurrentIndex( index );
    }

    connect( ui.editSlidesButton, SIGNAL(clicked()), this, SLOT(editCustomSlideShow()) );
}
Example #13
0
void MenuManager::setup(MenuItem* menuItems) const
{
    if (!menuItems)
        return; // empty menu bar

    QMenuBar* menuBar = getMainWindow()->menuBar();
    //menuBar->setUpdatesEnabled(false);

    QList<MenuItem*> items = menuItems->getItems();
    QList<QAction*> actions = menuBar->actions();
    for (QList<MenuItem*>::ConstIterator it = items.begin(); it != items.end(); ++it)
    {
        // search for the menu action
        QAction* action = findAction(actions, QString::fromAscii((*it)->command().c_str()));
        if (!action) {
            // There must be not more than one separator in the menu bar, so
            // we can safely remove it if available and append it at the end
            if ((*it)->command() == "Separator") {
                action = menuBar->addSeparator();
                action->setObjectName(QLatin1String("Separator"));
            }
            else {
                // create a new menu
                std::string menuName = (*it)->command();
                QMenu* menu = menuBar->addMenu(
                    QApplication::translate("Workbench", menuName.c_str(),
                                            0, QApplication::UnicodeUTF8));
                action = menu->menuAction();
                menu->setObjectName(QString::fromAscii(menuName.c_str()));
                action->setObjectName(QString::fromAscii(menuName.c_str()));
            }

            // set the menu user data
            action->setData(QString::fromAscii((*it)->command().c_str()));
        }
        else {
            // put the menu at the end
            menuBar->removeAction(action);
            menuBar->addAction(action);
            action->setVisible(true);
            int index = actions.indexOf(action);
            actions.removeAt(index);
        }

        // flll up the menu
        if (!action->isSeparator())
            setup(*it, action->menu());
    }

    // hide all menus which we don't need for the moment
    for (QList<QAction*>::Iterator it = actions.begin(); it != actions.end(); ++it) {
        (*it)->setVisible(false);
    }

    // enable update again
    //menuBar->setUpdatesEnabled(true);
}
bool DeclarativeTabModel::tabSort(const Tab &t1, const Tab &t2)
{
    int i1 = s_tabOrder.indexOf(t1.tabId());
    int i2 = s_tabOrder.indexOf(t2.tabId());
    if (i2 == -1) {
        return true;
    } else {
        return i1 < i2;
    }
}
Example #15
0
void QMenuBarPrivate::wceDestroyMenuBar()
{
    Q_Q(QMenuBar);
    int index = nativeMenuBars.indexOf(q);
    nativeMenuBars.removeAt(index);
    if (wce_menubar) {
        delete wce_menubar;
        wce_menubar = 0;
    }
}
Example #16
0
void Bataille::Tick(QList<Joueur *> Joueurs)
{
    for (int I = 0; I < m_ListeParticipants.count(); I++)
        for (int J = 0; J < m_ListeParticipants[I].m_ListeArmees.count(); J++)
            if (m_ListeParticipants[I].m_ListeArmees[J]->m_NbrPixels - 5 / m_ListeParticipants[I].m_Efficacite > 0)
                m_ListeParticipants[I].m_ListeArmees[J]->m_NbrPixels -= 5 / m_ListeParticipants[I].m_Efficacite;
            else
            {
                Joueurs[Joueurs.indexOf(m_ListeParticipants[I].m_Proprietaire)]->m_Armees.removeOne(m_ListeParticipants[I].m_ListeArmees[J]);
                m_ListeParticipants[I].m_ListeArmees.removeAt(J--);
            }

    for (int I = 0; I < m_ListeParticipants.count(); I++)
        if (m_ListeParticipants[I].m_ListeArmees.count() == 0)
            m_ListeParticipants.removeAt(I--);

    if (m_ListeParticipants.count() == 1)
        for (int I = 0; I < Joueurs[Joueurs.indexOf(m_ListeParticipants[0].m_Proprietaire)]->m_Armees.count(); I++)
            Joueurs[Joueurs.indexOf(m_ListeParticipants[0].m_Proprietaire)]->m_Armees[I]->m_BatailleEngagee = -1;
}
Example #17
0
void QEglFSWindow::lower()
{
    QList<QEGLPlatformWindow *> windows = screen()->windows();
    if (window()->type() != Qt::Desktop && windows.count() > 1) {
        int idx = windows.indexOf(this);
        if (idx > 0) {
            screen()->changeWindowIndex(this, idx - 1);
            QWindowSystemInterface::handleExposeEvent(windows.last()->window(), windows.last()->geometry());
        }
    }
}
int KeyConceptClass::readScore_DB()
{
    OntologyDB * db = new OntologyDB();
    db->openDB();

    QList<KeyConcept_DBFormat *> rs = db->getKeyconcept_classes(this->m_ontology->ontologyID);
    if(rs.size()!=measures.size()) return -1;

    cout<<"Assign scores to measures..."<<endl;

//    for(int i = 0;i<rs.size();i++){
//        for(int j=0;j<measures.size();j++){
//            if(measures[j].classname == rs[i]->classname){
//                measures[j].score = rs[i]->score;
//                measures[j].landmark = rs[i]->landmark;
//                measures[j].lastvisitedTime = rs[i]->lastVisitedTime;
//                measures[j].visitTimes = rs[i]->numberOfVisits;
//                break;
//            }
//        }
//    }

    QList<QString> cnames;
    for(int i=0; i<measures.size(); i++)cnames<<measures[i].classname;
    for(int i = 0; i<rs.size(); i++) {
        int idx = cnames.indexOf(rs[i]->classname);
        if(idx!=-1) {
            measures[idx].score = rs[i]->score;
            measures[idx].landmark = rs[i]->landmark;
            measures[idx].lastvisitedTime = rs[i]->lastVisitedTime;
            measures[idx].visitTimes = rs[i]->numberOfVisits;
        }
    }
    //Thing class not in database
    int idx = cnames.indexOf("Thing");
    measures[idx].score = 2;
    measures[idx].landmark = 5;

    db->closeDB();
    return 1;
}
Example #19
0
void PreferenceDialog::__updateFontSize(const QFont& font)
{
	QFontDatabase fontdatabase;
	QList<int> sizeList = fontdatabase.smoothSizes(font.family(), "");
	if (sizeList.empty()) sizeList = fontdatabase.pointSizes(font.family(), "");
	if (sizeList.empty()) sizeList = fontdatabase.standardSizes();
	if (!sizeList.contains(font.pointSize())) sizeList.append(font.pointSize());

	fontSize->clear();
	for (int size : sizeList) fontSize->addItem(QString::number(size), size);
	fontSize->setCurrentIndex(sizeList.indexOf(fontFamilly->currentFont().pointSize()));
}
Example #20
0
bool X11Helper::setLayout(const LayoutUnit& layout)
{
	QList<LayoutUnit> currentLayouts = getLayoutsList();
	int idx = currentLayouts.indexOf(layout);
	if( idx == -1 || idx >= X11Helper::MAX_GROUP_COUNT ) {
		kWarning() << "Layout" << layout.toString() << "is not found in current layout list"
								<< getLayoutsListAsString(currentLayouts);
		return false;
	}

	return X11Helper::setGroup((unsigned int)idx);
}
Example #21
0
void ChannelUrlSelectorEntry::punish(const QString& url) {
    LOG_TRACE(logger, "punish ...");
    QList<QString> urls = urlInformation.getUrls();
    if(!urls.contains(url)) {
        LOG_DEBUG(logger, "Url not contained in cache entry ...");
        return;
    }
    updateFitness();
    int urlPosition = urls.indexOf(url);
    double urlFitness = fitness.at(urlPosition);
    urlFitness-= punishmentFactor;
    fitness.replace(urlPosition,urlFitness);
}
Example #22
0
static QList<int> reindexList(const GlobalConfig *config, Phonon::Category category, QList<int>newOrder, bool output)
{
    Q_ASSERT(config);
#ifdef QT_NO_PHONON_AUDIOCAPTURE
    Q_ASSERT(output);
#endif

    /*QString sb;
    sb = QString("(Size %1)").arg(currentList.size());
    foreach (int i, currentList)
    sb += QString("%1, ").arg(i);
    fprintf(stderr, "=== Reindex Current: %s\n", sb.toUtf8().constData());
    sb = QString("(Size %1)").arg(newOrder.size());
    foreach (int i, newOrder)
    sb += QString("%1, ").arg(i);
    fprintf(stderr, "=== Reindex Before : %s\n", sb.toUtf8().constData());*/

    QList<int> currentList;
    if (output)
        currentList = config->audioOutputDeviceListFor(category, GlobalConfig::ShowUnavailableDevices|GlobalConfig::ShowAdvancedDevices);
#ifndef QT_NO_PHONON_AUDIOCAPTURE
    else
        currentList = config->audioCaptureDeviceListFor(category, GlobalConfig::ShowUnavailableDevices|GlobalConfig::ShowAdvancedDevices);
#endif

    QList<int> newList;

    foreach (int i, newOrder) {
        int found = currentList.indexOf(i);
        if (found < 0) {
            // It's not in the list, so something is odd (e.g. client error). Ignore it.
            continue;
        }

        // Iterate through the list from this point onward. If there are hidden devices
        // immediately following, take them too.
        newList.append(currentList.takeAt(found));
        while (found < currentList.size()) {
            bool hidden = true;
            if (output)
                hidden = isHiddenAudioOutputDevice(config, currentList.at(found));
#ifndef QT_NO_PHONON_AUDIOCAPTURE
            else
                hidden = isHiddenAudioCaptureDevice(config, currentList.at(found));
#endif

            if (!hidden)
                break;
            newList.append(currentList.takeAt(found));
        }
    }
Example #23
0
void TestShapeReorderCommand::testSendToBack()
{
    MockShape shape1, shape2, shape3;

    shape1.setSize(QSizeF(100, 100));
    shape1.setZIndex(1);
    shape2.setSize(QSizeF(100, 100));
    shape2.setZIndex(2);
    shape3.setSize(QSizeF(100, 100));
    shape3.setZIndex(3);
    QList<KShape*> shapes;
    shapes.append(&shape1);
    shapes.append(&shape2);
    shapes.append(&shape3);

    MockCanvas canvas;
    KShapeManager manager(&canvas, shapes);

    qSort(shapes.begin(), shapes.end(), KShape::compareShapeZIndex);
    QCOMPARE(shapes.indexOf(&shape1), 0);
    QCOMPARE(shapes.indexOf(&shape2), 1);
    QCOMPARE(shapes.indexOf(&shape3), 2);

    QList<KShape*> selectedShapes;
    selectedShapes.append(&shape3);

    QUndoCommand * cmd = KShapeReorderCommand::createCommand(selectedShapes, &manager, KShapeReorderCommand::SendToBack);
    cmd->redo();

    qSort(shapes.begin(), shapes.end(), KShape::compareShapeZIndex);
    QCOMPARE(shapes.indexOf(&shape3), 0);
    QCOMPARE(shapes.indexOf(&shape1), 1);
    QCOMPARE(shapes.indexOf(&shape2), 2);

    delete cmd;
}
Example #24
0
/*!
    \internal
*/
bool QImageReaderPrivate::initHandler()
{
    // check some preconditions
    if (!device || (!deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly))) {
        imageReaderError = QImageReader::DeviceError;
        errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Invalid device"));
        return false;
    }

    // probe the file extension
    if (deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly) && autoDetectImageFormat) {
        QList<QByteArray> extensions = QImageReader::supportedImageFormats();
        if (!format.isEmpty()) {
            // Try the most probable extension first
            int currentFormatIndex = extensions.indexOf(format.toLower());
            if (currentFormatIndex > 0)
                extensions.swap(0, currentFormatIndex);
        }

        int currentExtension = 0;

        QFile *file = static_cast<QFile *>(device);
        QString fileName = file->fileName();

        do {
            file->setFileName(fileName + QLatin1Char('.')
                    + QString::fromLatin1(extensions.at(currentExtension++).constData()));
            file->open(QIODevice::ReadOnly);
        } while (!file->isOpen() && currentExtension < extensions.size());

        if (!device->isOpen()) {
            imageReaderError = QImageReader::FileNotFoundError;
            errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "File not found"));
            file->setFileName(fileName); // restore the old file name
            return false;
        }
    }

    // assign a handler
    if (!handler && (handler = createReadHandlerHelper(device, format, autoDetectImageFormat, ignoresFormatAndExtension)) == 0) {
        imageReaderError = QImageReader::UnsupportedFormatError;
        errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Unsupported image format"));
        return false;
    }
    return true;
}
Example #25
0
QString Json::stringify(const QVariant &variant, int indent)
{
  QString res;

  if((variant.type() == QVariant::List) || (variant.type() == QVariant::StringList)) {
    res = QString(" ").repeated(indent) + "[\n";

    QList<QVariant> list = variant.toList();
    foreach(QVariant var, list) {
      res += stringify(var, indent + 2);

      if(list.indexOf(var) < list.size() - 1) {
        res += ",";
      }

      res += "\n";
    }
void DoubleTabWidget::mousePressEvent(QMouseEvent *event)
{
    // todo:
    // the even wasn't accepted/ignored in a consistent way
    // now the event is accepted everywhere were it hitted something interesting
    // and otherwise ignored
    // should not make any difference
    QPair<HitArea, int> hit = convertPosToTab(event->pos());
    if (hit.first == HITTAB) {
        if (m_currentIndex != m_currentTabIndices.at(hit.second)) {
            m_currentIndex = m_currentTabIndices.at(hit.second);
            update();
            event->accept();
            emit currentIndexChanged(m_currentIndex, m_tabs.at(m_currentIndex).currentSubTab);
            return;
        }
    } else if (hit.first == HITOVERFLOW) {
        QMenu overflowMenu;
        QList<QAction *> actions;
        for (int i = m_lastVisibleIndex + 1; i < m_tabs.size(); ++i) {
            actions << overflowMenu.addAction(m_tabs.at(m_currentTabIndices.at(i)).displayName());
        }
        if (QAction *action = overflowMenu.exec(event->globalPos())) { // todo used different position before
            int index = m_currentTabIndices.at(actions.indexOf(action) + m_lastVisibleIndex + 1);
            if (m_currentIndex != index) {
                m_currentIndex = index;
                update();
                event->accept();
                emit currentIndexChanged(m_currentIndex, m_tabs.at(m_currentIndex).currentSubTab);
                return;
            }
        }
    } else if (hit.first == HITSUBTAB) {
        if (m_tabs[m_currentIndex].currentSubTab != hit.second) {
            m_tabs[m_currentIndex].currentSubTab = hit.second;
            update();
            // todo next two lines were outside the if leading to
            // unnecessary (?) signal emissions?
            event->accept();
            emit currentIndexChanged(m_currentIndex, m_tabs.at(m_currentIndex).currentSubTab);
            return;
        }
    }
    event->ignore();
}
Example #27
0
void MainTabs::onDeletedTabSelected(QAction *action)
{
    if (tabCount > maxTabCount) {
        logger->logError(tr("Reached the maximum number of allowed tabs, cannot revive the deleted tab."));
        return;
    }

    QList<QAction*> actions = tabHeaderContextMenu->actions();
    int index = actions.indexOf(action);
    if (index == -1) // need to do that because the actions from the submenu seem to be arriving here as well ???
        return;
    if (index > 2) {
        index = index - 3; // decreasing the index due to newMenu + title + separator
        guiHelper->reviveTab(index);
    } else {
        qCritical() << tr("[MainTabs::onDeletedTabSelected] index not found T_T");
    }
}
Example #28
0
void FocusChain::moveAfterClientInChain(Client *client, Client *reference, QList<Client *> &chain)
{
    if (!chain.contains(reference)) {
        return;
    }
    if (Client::belongToSameApplication(reference, client)) {
        chain.removeAll(client);
        chain.insert(chain.indexOf(reference), client);
    } else {
        chain.removeAll(client);
        for (int i = chain.size() - 1; i >= 0; --i) {
            if (Client::belongToSameApplication(reference, chain.at(i))) {
                chain.insert(i, client);
                break;
            }
        }
    }
}
int Dialog::showMessageDialog(const QString& text, int icon, const QString& caption, const QStringList& buttons, int defaultIndex) const
{
    QMessageBox messageBox((QMessageBox::Icon)icon, caption.isEmpty() ? QCoreApplication::applicationName() : caption,
                           text, QMessageBox::NoButton, QApplication::activeWindow());
    QList<QAbstractButton*> buttonList;

    for (int i = 0; i < buttons.count(); ++i)
    {
        buttonList.append(
            (QAbstractButton*)messageBox.addButton(buttons[i], i == defaultIndex ? QMessageBox::AcceptRole : QMessageBox::RejectRole)
        );
    }

    if (defaultIndex >= 0 && defaultIndex < buttonList.count())
        messageBox.setDefaultButton((QPushButton*)buttonList[defaultIndex]);

    messageBox.exec();
    return buttonList.indexOf(messageBox.clickedButton());
}
Example #30
0
void ApiTraceModel::stateSetOnEvent(ApiTraceEvent *event)
{
    if (!event)
        return;

    if (event->type() == ApiTraceEvent::Call) {
        ApiTraceCall *call = static_cast<ApiTraceCall*>(event);
        ApiTraceFrame *frame = call->parentFrame;
        int row = frame->calls.indexOf(call);
        QModelIndex index = createIndex(row, 0, call);
        emit dataChanged(index, index);
    } else if (event->type() == ApiTraceEvent::Frame) {
        ApiTraceFrame *frame = static_cast<ApiTraceFrame*>(event);
        const QList<ApiTraceFrame*> frames = m_trace->frames();
        int row = frames.indexOf(frame);
        QModelIndex index = createIndex(row, 0, frame);
        emit dataChanged(index, index);
    }
}