void TaskView::updateWatcher(void)
{
    // In case a child of the TaskView has the focus and get hidden we have
    // to make sure that set the focus on a widget that won't be hidden or
    // deleted because otherwise Qt may forward the focus via focusNextPrevChild()
    // to the mdi area which may switch to another mdi view which is not an
    // acceptable behaviour.
    QWidget *fw = QApplication::focusWidget();
    if (!fw)
        this->setFocus();
    QPointer<QWidget> fwp = fw;
    while (fw &&  !fw->isWindow()) {
        if (fw == this) {
            this->setFocus();
            break;
        }
        fw = fw->parentWidget();
    }

    // add all widgets for all watcher to the task view
    for (std::vector<TaskWatcher*>::iterator it=ActiveWatcher.begin();it!=ActiveWatcher.end();++it) {
        bool match = (*it)->shouldShow();
        std::vector<QWidget*> &cont = (*it)->getWatcherContent();
        for (std::vector<QWidget*>::iterator it2=cont.begin();it2!=cont.end();++it2) {
            if (match)
                (*it2)->show();
            else
                (*it2)->hide();
        }
    }

    // In case the previous widget that had the focus is still visible
    // give it the focus back.
    if (fwp && fwp->isVisible())
        fwp->setFocus();
}
示例#2
0
void TabBar::mouseMoveEvent (QMouseEvent *event)
{
    if (!dragStartPosition_.isNull()
        && (event->pos() - dragStartPosition_).manhattanLength() >= QApplication::startDragDistance())
    {
      dragStarted_ = true;
    }

    /* since Wayland has a serious issue related to QDrag that interferes with
       dropping tabs outside all windows, we don't enable tab DND without X11 */
    if (!noTabDND_
        && (event->buttons() & Qt::LeftButton)
        && dragStarted_
        && !window()->geometry().contains (event->globalPos()))
    {
        int index = currentIndex();
        if (index == -1)
        {
            event->accept();
            return;
        }

        QPointer<QDrag> drag = new QDrag (this);
        QMimeData *mimeData = new QMimeData;
        QByteArray array;
        array.append (QString ("%1+%2").arg (window()->winId()).arg (index));
        mimeData->setData ("application/featherpad-tab", array);
        drag->setMimeData (mimeData);
        QPixmap px = QIcon (":icons/tab.svg").pixmap (22, 22);
        drag->setPixmap (px);
        drag->setHotSpot (QPoint (px.width()/2, px.height()));
        Qt::DropAction dragged = drag->exec (Qt::MoveAction);
        if (dragged != Qt::MoveAction)
        {
            /* A tab is dropped outside all windows. WARNING: Under Enlightenment,
               this may be Qt::CopyAction, not IgnoreAction (an E bug). */
            if (count() > 1)
                emit tabDetached();
            else
                finishMouseMoveEvent();
            event->accept();
        }
        else // a tab is dropped into another window
            event->accept();
        drag->deleteLater();
    }
    else
    {
        QTabBar::mouseMoveEvent(event);
        int index = tabAt (event->pos());
        if (index > -1)
            QToolTip::showText (event->globalPos(), tabToolTip (index));
        else
            QToolTip::hideText();
    }
}
void Akregator::SubscriptionListView::showHeaderMenu( const QPoint& pos )
{
    if( ! model() )
        return;

    QPointer<KMenu> menu = new KMenu( this );
    menu->addTitle( i18n( "Columns" ) );
    menu->setAttribute( Qt::WA_DeleteOnClose );
    connect(menu, SIGNAL( triggered( QAction* ) ), this, SLOT( headerMenuItemTriggered( QAction* ) ) );

    for (int i = 0; i < model()->columnCount(); i++)
    {
        if ( SubscriptionListModel::TitleColumn == i ) {
            continue;
        }
        QString col = model()->headerData( i, Qt::Horizontal, Qt::DisplayRole ).toString();
        QAction* act = menu->addAction( col );
        act->setCheckable( true );
        act->setChecked( !header()->isSectionHidden( i ) );
        act->setData( i );
    }

    menu->popup( header()->mapToGlobal( pos ) );
}
示例#4
0
MapGraphicsView::~MapGraphicsView()
{
    qDebug() << this << "Destructing";
    //When we die, take all of our tile objects with us...
    foreach(MapTileGraphicsObject * tileObject, _tileObjects)
    {
        if (!_childScene.isNull())
            _childScene->removeItem(tileObject);
        delete tileObject;
    }
    _tileObjects.clear();

    if (!_tileSource.isNull())
    {
        //Find the tileSource's thread
        QPointer<QThread> tileSourceThread = _tileSource->thread();

        /*
         Clear the QSharedPointer to the tilesource. Unless there's a serious problem, we should be the
         last thing holding that reference and we expect it to be deleted
        */
        _tileSource.clear();

        //After the tilesource is deleted, we wait for the thread it was running in to shut down
        int count = 0;
        const int maxCount = 100;
        while (!tileSourceThread.isNull() && !tileSourceThread->wait(100))
        {
            //We have to process events while it's shutting down in case it uses signals/slots to shut down
            //Hint: it does
            QCoreApplication::processEvents(QEventLoop::ExcludeSocketNotifiers | QEventLoop::ExcludeUserInputEvents);
            if (++count == maxCount)
                break;
        }
    }
}
示例#5
0
void WicdApplet::createAdhocDialog() const
{
    QPointer<AdhocDialog> dialog = new AdhocDialog();
    if (dialog->exec() == QDialog::Accepted) {
        KConfigGroup op = m_wicdService->operationDescription("createAdHocNetwork");
        op.writeEntry("essid", dialog->essid());
        op.writeEntry("channel", dialog->channel());
        op.writeEntry("ip", dialog->ip());
        op.writeEntry("key", dialog->key());
        op.writeEntry("wep", dialog->wep());
        m_wicdService->startOperationCall(op);
    }
    delete dialog;
}
    static void mouseMove(JNIEnv */*env*/, jobject /*thiz*/, jint /*winId*/, jint x, jint y)
    {

        if (m_ignoreMouseEvents)
            return;

        QPoint globalPos(x,y);
        QWindow *tlw = m_mouseGrabber.data();
        if (!tlw)
            tlw = topLevelWindowAt(globalPos);
        QPoint localPos = tlw ? (globalPos-tlw->position()) : globalPos;
        QWindowSystemInterface::handleMouseEvent(tlw,
                                                 localPos,
                                                 globalPos,
                                                 Qt::MouseButtons(Qt::LeftButton));
    }
示例#7
0
void GraphDraw::doClickSelection(const QPointF &point)
{
    const bool ctrlDown = QApplication::keyboardModifiers() & Qt::ControlModifier;
    const auto objs = this->items(this->mapFromScene(point));

    //nothing selected, clear the last selected endpoint
    if (objs.empty()) _lastClickSelectEp = GraphConnectionEndpoint();

    //connection creation logic
    if (not ctrlDown and not objs.empty())
    {
        auto topObj = dynamic_cast<GraphObject *>(objs.front());
        if (topObj == nullptr) return;
        GraphConnectionEndpoint thisEp(topObj, topObj->isPointingToConnectable(topObj->mapFromParent(point)));

        //valid keys, attempt to make a connection
        QPointer<GraphConnection> conn;
        if (thisEp.isValid() and _lastClickSelectEp.isValid() and not (thisEp == _lastClickSelectEp) and //end points valid
            (_lastClickSelectEp.getConnectableAttrs().direction == GRAPH_CONN_OUTPUT or _lastClickSelectEp.getConnectableAttrs().direction == GRAPH_CONN_SIGNAL) and //last endpoint is output
            (thisEp.getConnectableAttrs().direction == GRAPH_CONN_INPUT or thisEp.getConnectableAttrs().direction == GRAPH_CONN_SLOT)) //this click endpoint is input
        {
            try
            {
                conn = this->getGraphEditor()->makeConnection(thisEp, _lastClickSelectEp);
                this->getGraphEditor()->handleStateChange(GraphState("connect-arrow", tr("Connect %1[%2] to %3[%4]").arg(
                    conn->getOutputEndpoint().getObj()->getId(),
                    conn->getOutputEndpoint().getKey().id,
                    conn->getInputEndpoint().getObj()->getId(),
                    conn->getInputEndpoint().getKey().id
                )));
            }
            catch (const Pothos::Exception &ex)
            {
                poco_warning(Poco::Logger::get("PothosGui.GraphDraw.connect"), Poco::format("Cannot connect port %s[%s] to port %s[%s]: %s",
                    _lastClickSelectEp.getObj()->getId().toStdString(),
                    _lastClickSelectEp.getKey().id.toStdString(),
                    thisEp.getObj()->getId().toStdString(),
                    thisEp.getKey().id.toStdString(),
                    ex.message()));
            }
        }

        //cleanup after new connection
        if (not conn.isNull())
        {
            _lastClickSelectEp = GraphConnectionEndpoint();
            this->deselectAllObjs();
        }
        //otherwise save the click select
        else
        {
            _lastClickSelectEp = thisEp;
        }
    }
}
示例#8
0
void EffectView::contextMenuEvent( QContextMenuEvent * )
{
	QPointer<CaptionMenu> contextMenu = new CaptionMenu( model()->displayName(), this );
	contextMenu->addAction( embed::getIconPixmap( "arp_up" ),
						tr( "Move &up" ),
						this, SLOT( moveUp() ) );
	contextMenu->addAction( embed::getIconPixmap( "arp_down" ),
						tr( "Move &down" ),
						this, SLOT( moveDown() ) );
	contextMenu->addSeparator();
	contextMenu->addAction( embed::getIconPixmap( "cancel" ),
						tr( "&Remove this plugin" ),
						this, SLOT( deletePlugin() ) );
	contextMenu->addSeparator();
	contextMenu->addHelpAction();
	contextMenu->exec( QCursor::pos() );
	delete contextMenu;
}
示例#9
0
void PresentationAudioPage::slotSoundFilesButtonLoad()
{
    QPointer<QFileDialog> dlg = new QFileDialog(this, i18n("Load playlist"),
                                                QString(), i18n("Playlist (*.m3u)"));
    dlg->setAcceptMode(QFileDialog::AcceptOpen);
    dlg->setFileMode(QFileDialog::ExistingFile);

    if (dlg->exec() != QDialog::Accepted)
    {
        delete dlg;
        return;
    }

    QString filename = dlg->selectedFiles().isEmpty() ? QString() : dlg->selectedFiles().at(0);

    if (!filename.isEmpty())
    {
        QFile file(filename);

        if (file.open(QIODevice::ReadOnly|QIODevice::Text))
        {
            QTextStream in(&file);
            QList<QUrl> playlistFiles;

            while (!in.atEnd())
            {
                QString line = in.readLine();

                // we ignore the extended information of the m3u playlist file
                if (line.startsWith(QLatin1Char('#')) || line.isEmpty())
                    continue;

                QUrl fUrl(line);

                if (fUrl.isValid())
                {
                    if (fUrl.isLocalFile())
                    {
                        playlistFiles << fUrl;
                    }
                }
            }

            if (!playlistFiles.isEmpty())
            {
                m_SoundFilesListBox->clear();
                addItems(playlistFiles);
                updateFileList();
            }
        }
    }

    delete dlg;
}
示例#10
0
void KateGlobal::configDialog(QWidget *parent)
{
    QPointer<KPageDialog> kd = new KPageDialog(parent);
    kd->setCaption( i18n("Configure") );
    kd->setButtons( KDialog::Ok | KDialog::Cancel | KDialog::Apply | KDialog::Help );
    kd->setFaceType( KPageDialog::List );
    kd->setHelp( QString(), KGlobal::mainComponent().componentName() );

    QList<KTextEditor::ConfigPage*> editorPages;

    for (int i = 0; i < configPages (); ++i)
    {
        const QString name = configPageName (i);

        QFrame *page = new QFrame();

        KPageWidgetItem *item = kd->addPage( page, name );
        item->setHeader( configPageFullName (i) );
        item->setIcon( configPageIcon(i) );

        QVBoxLayout *topLayout = new QVBoxLayout( page );
        topLayout->setMargin( 0 );

        KTextEditor::ConfigPage *cp = configPage(i, page);
        connect(kd, SIGNAL(applyClicked  ( )), cp, SLOT(apply()));
        topLayout->addWidget( cp);
        editorPages.append (cp);
    }

    if (kd->exec() && kd)
    {
        KateGlobalConfig::global()->configStart ();
        KateDocumentConfig::global()->configStart ();
        KateViewConfig::global()->configStart ();
        KateRendererConfig::global()->configStart ();

        for (int i=0; i < editorPages.count(); ++i)
        {
            editorPages.at(i)->apply();
        }

        KateGlobalConfig::global()->configEnd ();
        KateDocumentConfig::global()->configEnd ();
        KateViewConfig::global()->configEnd ();
        KateRendererConfig::global()->configEnd ();
    }

    delete kd;
}
示例#11
0
void NamedAreaDialog::slotNew()
{
    QPointer<EditNamedAreaDialog> dialog = new EditNamedAreaDialog(this, m_selection);
    dialog->setCaption(i18n("New Named Area"));
    dialog->setRegion(*m_selection);
    dialog->exec();
    if (dialog->result() == Rejected)
        return;
    if (dialog->areaName().isEmpty())
        return;

    m_list->addItem(dialog->areaName());
    QList<QListWidgetItem*> items = m_list->findItems(dialog->areaName(),
                                    Qt::MatchExactly | Qt::MatchCaseSensitive);
    m_list->setCurrentItem(items.first());
    displayAreaValues(dialog->areaName());
    delete dialog;

    enableButtonOk(true);
    enableButton(KDialog::User1, true);
    enableButton(KDialog::User2, true);
}
示例#12
0
void ImportMegaLinksDialog::on_bLocalFolder_clicked()
{
    QString defaultPath = ui->eLocalFolder->text().trimmed();
    if (!defaultPath.size())
    {
#ifdef WIN32
    #if QT_VERSION < 0x050000
        defaultPath = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
    #else
        defaultPath = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0];
    #endif
#else
    #if QT_VERSION < 0x050000
        defaultPath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
    #else
        defaultPath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation)[0];
    #endif
#endif
    }

#ifndef _WIN32
    QPointer<MultiQFileDialog> dialog = new MultiQFileDialog(0,  tr("Select local folder"), defaultPath, false);
    dialog->setOptions(QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    dialog->setFileMode(QFileDialog::DirectoryOnly);
    int result = dialog->exec();
    if (!dialog || result != QDialog::Accepted || dialog->selectedFiles().isEmpty())
    {
        delete dialog;
        return;
    }
    QString path = dialog->selectedFiles().value(0);
    delete dialog;
#else
    QString path = QFileDialog::getExistingDirectory(0,  tr("Select local folder"), defaultPath);
#endif
    if (path.length())
    {
        path = QDir::toNativeSeparators(path);
        QDir dir(path);
        if (!dir.exists() && !dir.mkpath(QString::fromAscii(".")))
        {
            return;
        }

        QTemporaryFile test(path + QDir::separator());
        if (!test.open())
        {
            QMessageBox::critical(window(), tr("Error"), tr("You don't have write permissions in this local folder."));
            return;
        }

        ui->eLocalFolder->setText(path);
    }
}
示例#13
0
文件: dllmain.cpp 项目: ellis/gcead
IdacDriverUsbEs* wrapper() {
	LOG(1, "wrapper()");

	if (g_manager == NULL)
		return NULL;

	if (g_wrapper == NULL) {
		IdacDriver2* driver2 = dynamic_cast<IdacDriver2*>(g_manager->driver());
		IdacDriver4* driver4 = dynamic_cast<IdacDriver4*>(g_manager->driver());
		if (driver2 != NULL) {
			g_wrapper = new IdacDriver2Es(driver2, driver2->defaultChannelSettings());
		}
		else if (driver4 != NULL)
			g_wrapper = new IdacDriver4Es(driver4, driver4->defaultChannelSettings());
	}
	return g_wrapper;
}
示例#14
0
	void onStrokingOrToolEditingChanged()
	{
		if (!mTool)
			return;

		bool strokingOrToolEditing = mStroking || mTool->isEditing();

		if (mStrokingOrToolEditing != strokingOrToolEditing) {
			if (strokingOrToolEditing) {
				mCanvas->document()->layerScene()->abortThumbnailUpdate();
				mCanvas->disableUndoRedo();
			} else {
				mCanvas->enableUndoRedo();
			}
			mStrokingOrToolEditing = strokingOrToolEditing;
		}
	}
示例#15
0
void ControllerView::contextMenuEvent( QContextMenuEvent * )
{
	QPointer<CaptionMenu> contextMenu = new CaptionMenu( model()->displayName(), this );
	contextMenu->addAction( embed::getIconPixmap( "cancel" ),
						tr( "&Remove this controller" ),
						this, SLOT( deleteController() ) );
	contextMenu->addAction( tr("Re&name this controller"), this, SLOT( renameController() ));
	contextMenu->addSeparator();
	contextMenu->addHelpAction();
	contextMenu->exec( QCursor::pos() );
	delete contextMenu;
}
示例#16
0
void UserAgentManager::showSettings()
{
    QPointer<KDialog> dialog = new KDialog(m_uaTab.data());
    dialog->setCaption(i18nc("@title:window", "User Agent Settings"));
    dialog->setButtons(KDialog::Ok);

    UserAgentWidget widget;
    dialog->setMainWidget(&widget);
    dialog->exec();

    dialog->deleteLater();
}
示例#17
0
void RoutingInputWidget::openTargetSelectionDialog()
{
    QPointer<GoToDialog> dialog = new GoToDialog( d->m_marbleModel, this );
    dialog->setWindowTitle( tr( "Choose Placemark" ) );
    dialog->setShowRoutingItems( false );
    dialog->setSearchEnabled( false );
    if ( dialog->exec() == QDialog::Accepted ) {
        const GeoDataCoordinates coordinates = dialog->coordinates();
        setTargetPosition( coordinates );
    }
    delete dialog;
}
示例#18
0
DNGImageDialog::DNGImageDialog(QWidget* parent, KIPI::Interface* iface)
    : d(new DNGImageDialogPrivate)
{
    QStringList patternList;
    QString     allPictures;
    QString     allSupportedFiles;

    patternList = KImageIO::pattern(KImageIO::Reading).split('\n', QString::SkipEmptyParts);

    // All Images from list must been always the first entry given by KDE API
    allPictures = patternList[0];

    allPictures.insert(allPictures.indexOf("|"), QString(KDcraw::rawFiles()) + QString(" *.JPE *.TIF"));
    patternList.removeAll(patternList[0]);
    patternList.prepend(allPictures);

    allSupportedFiles = i18n("%1|All supported files", 
                               QString("*.") + QString(KImageIO::types(KImageIO::Reading).join(" *."))
                             + QString(" ")  + QString(KDcraw::rawFiles())
                             + QString(" *.JPE *.TIF ")
                             + QString(picasaweb_video_extentions));

    patternList.prepend(allSupportedFiles);
    kDebug() << allSupportedFiles;

    // Added RAW file formats supported by dcraw program like a type mime.
    // Nota: we cannot use here "image/x-raw" type mime from KDE because it uncomplete
    // or unavailable(see file #121242 in B.K.O).
    patternList.append(i18n("%1|Camera RAW files", QString(KDcraw::rawFiles())));

    patternList.append(i18n("%1|Video files", QString(picasaweb_video_extentions)));

    QString fileFormats = patternList.join("\n");

    QPointer<KFileDialog> dlg = new KFileDialog(iface ? iface->currentAlbum().path().path()
                                                         : KGlobalSettings::documentPath(),
                                                fileFormats, parent);
    KIPIPlugins::ImageDialogPreview *preview = new KIPIPlugins::ImageDialogPreview(iface, dlg);
    dlg->setPreviewWidget(preview);
    dlg->setOperationMode(KFileDialog::Opening);

    dlg->setMode( KFile::Files );
    dlg->setWindowTitle(i18n("Select Images"));
    dlg->exec();
    d->urls = dlg->selectedUrls();

    delete dlg;
}
示例#19
0
bool AlbumPropsEdit::createNew(PAlbum* parent, QString& title, QString& comments,
                               QDate& date, QString& category, QStringList& albumCategories)
{
    QPointer<AlbumPropsEdit> dlg = new AlbumPropsEdit(parent, true);

    bool ok = dlg->exec() == QDialog::Accepted;

    title           = dlg->title();
    comments        = dlg->comments();
    date            = dlg->date();
    category        = dlg->category();
    albumCategories = dlg->albumCategories();

    delete dlg;
    return ok;
}
void ControlSingleton::showDialog(Gui::TaskView::TaskDialog *dlg)
{
    // only one dialog at a time
    assert(!ActiveDialog || ActiveDialog==dlg);
    Gui::DockWnd::CombiView* pcCombiView = qobject_cast<Gui::DockWnd::CombiView*>
        (Gui::DockWindowManager::instance()->getDockWindow("Combo View"));
    // should return the pointer to combo view
    if (pcCombiView) {
        pcCombiView->showDialog(dlg);
        // make sure that the combo view is shown
        QDockWidget* dw = qobject_cast<QDockWidget*>(pcCombiView->parentWidget());
        if (dw) {
            dw->setVisible(true);
            dw->toggleViewAction()->setVisible(true);
            dw->setFeatures(QDockWidget::DockWidgetMovable|QDockWidget::DockWidgetFloatable);
        }

        if (ActiveDialog == dlg)
            return; // dialog is already defined
        ActiveDialog = dlg;
        connect(dlg, SIGNAL(destroyed()), this, SLOT(closedDialog()));
    }
    // not all workbenches have the combo view enabled
    else if (!_taskPanel) {
        QDockWidget* dw = new QDockWidget();
        dw->setWindowTitle(tr("Task panel"));
        dw->setFeatures(QDockWidget::DockWidgetMovable);
        _taskPanel = new Gui::TaskView::TaskView(dw);
        dw->setWidget(_taskPanel);
        _taskPanel->showDialog(dlg);
        getMainWindow()->addDockWidget(Qt::LeftDockWidgetArea, dw);
        connect(dlg, SIGNAL(destroyed()), dw, SLOT(deleteLater()));

        // if we have the normal tree view available then just tabify with it
        QWidget* treeView = Gui::DockWindowManager::instance()->getDockWindow("Tree view");
        QDockWidget* par = treeView ? qobject_cast<QDockWidget*>(treeView->parent()) : 0;
        if (par && par->isVisible()) {
            getMainWindow()->tabifyDockWidget(par, dw);
            qApp->processEvents(); // make sure that the task panel is tabified now
            dw->show();
            dw->raise();
        }
    }
}
TEST(TestWindow, test_open_and_close_window)
{
  QPointer<PaintingWindow> window = qobject_cast<PaintingWindow *>(
    create_window(300, 300, "My Window", 50, 50)
  );
  QPointer<QWidget> scroll_area(window->scrollArea());

  // Check window dimensions.
  EXPECT_EQ(get_width(window), window->width());
  EXPECT_EQ(get_height(window), window->height());
  EXPECT_EQ(get_sizes(window),
            Vector2i(window->width(), window->height()));
  // Check window title.
  EXPECT_EQ(scroll_area->windowTitle(), QString("My Window"));
  // Check window position.
  EXPECT_EQ(window->x(), 50);
  EXPECT_EQ(window->y(), 50);

  // Check that the widget gets destroyed when we close the window.
  close_window(window);
  millisleep(50);
  EXPECT_TRUE(scroll_area.isNull());
  EXPECT_TRUE(window.isNull());
}
示例#22
0
bool AddToArchive::showAddDialog()
{
    qCDebug(ARK) << "Opening add dialog";

    QPointer<Kerfuffle::CreateDialog> dialog = new Kerfuffle::CreateDialog(
        Q_NULLPTR, // parent
        i18n("Compress to Archive"), // caption
        QUrl::fromLocalFile(m_firstPath)); // startDir

    bool ret = dialog.data()->exec();

    if (ret) {
        qCDebug(ARK) << "CreateDialog returned URL:" << dialog.data()->selectedUrl().toString();
        qCDebug(ARK) << "CreateDialog returned mime:" << dialog.data()->currentMimeType().name();
        setFilename(dialog.data()->selectedUrl());
        setMimeType(dialog.data()->currentMimeType().name());
        setPassword(dialog.data()->password());
        setHeaderEncryptionEnabled(dialog.data()->isHeaderEncryptionEnabled());
    }

    delete dialog.data();

    return ret;
}
示例#23
0
void NamedAreaDialog::slotEdit()
{
    QListWidgetItem* item = m_list->currentItem();
    if (item->text().isEmpty())
        return;

    QPointer<EditNamedAreaDialog> dialog = new EditNamedAreaDialog(this, m_selection);
    dialog->setCaption(i18n("Edit Named Area"));
    dialog->setAreaName(item->text());
    dialog->exec();
    if (dialog->result() == Rejected)
        return;

    item->setText(dialog->areaName());
    displayAreaValues(dialog->areaName());
    delete dialog;
}
QPointer<TrainTimetable> PlkApiResponseParser::parseResponse(QByteArray response){


    QPointer<TrainTimetable> timetable = new TrainTimetable();

    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(response, &err);
    QJsonObject json_root = doc.object();
    QJsonArray json_connections = json_root["P"].toArray();
    QString json_travel_source =  json_root["S"].toString();
    QString json_travel_destination =  json_root["T"].toString();

    if(err.error != QJsonParseError::NoError){
        throw new NotJsonResponseException("The response drom the server did not contain valid JSON. " + err.errorString());
    }

    for(int i=0; i< json_connections.size(); i++){

        QJsonObject single_result = json_connections[i].toObject();

        QPointer<TrainConnection> connection = new TrainConnection();
        connection->setSource(json_travel_source);
        connection->setDestination(json_travel_destination);
        connection->setJourneyStartDate(QDateTime::fromString(single_result["O"].toString(), "dd.MM.yyyy HH:mm"));
        connection->setJourneyEndDate(QDateTime::fromString(single_result["P"].toString(), "dd.MM.yyyy HH:mm"));



        QStringList train_types;
        QJsonArray trains = single_result["N"].toArray();
        for(int j=0;j<trains.size();j++){
            QJsonObject curr_train = trains[j].toObject();
            train_types.append(curr_train["P"].toString());
        }
        connection->setCarrierName(train_types.join(","));
        timetable->addConnection(connection);
    }


    return timetable;
}
示例#25
0
void SessionManager::manageSessions()
{
    kDebug() << "OK ,manage session..";
    
    QPointer<KDialog> dialog = new KDialog();
    dialog->setCaption(i18nc("@title:window", "Manage Session"));
    dialog->setButtons(KDialog::Ok | KDialog::Close);

    dialog->button(KDialog::Ok)->setIcon(KIcon("system-run"));
    dialog->button(KDialog::Ok)->setText(i18n("Load"));

    SessionWidget widg;
    dialog->setMainWidget(&widg);
    
    connect(dialog, SIGNAL(okClicked()), &widg, SLOT(loadSession()));
    dialog->exec();
}
示例#26
0
int main(int argc, char *argv[])
{
#ifdef Q_OS_WIN
    signal(SIGBREAK, signalHandler);
#else
    signal(SIGHUP, signalHandler);
#endif
    signal(SIGINT, signalHandler);

    qInstallMessageHandler(messageOutput);

    QCoreApplication a(argc, argv);

    if (!QDir("../data/").exists())
    {
        if (!QDir().mkdir("../data/"))
        {
            DEBUG_FUNCTION("Cant open data folder! Exiting...");
            return 0;
        }
    }

    QFile file("../data/log.txt");

    log_file = &file;

    if (!log_file->open(QFile::WriteOnly | QFile::Text | QFile::Append))
    {
        qInstallMessageHandler(nullptr);
        qDebug() << "Couldn't log to file!";
    }

    QSettings settings("../data/settings.ini", QSettings::IniFormat);

    global_settings = &settings;

    DEBUG_FUNCTION("Session started!");

    SslServer server;
    Q_UNUSED(server)

    return a.exec();
}
示例#27
0
void KUrlNavigator::Private::openPathSelectorMenu()
{
    if (m_navButtons.count() <= 0) {
        return;
    }

    const KUrl firstVisibleUrl = m_navButtons.first()->url();

    QString spacer;
    QPointer<KMenu> popup = new KMenu(q);
    popup->setLayoutDirection(Qt::LeftToRight);

    const QString placePath = retrievePlacePath();
    int idx = placePath.count(QLatin1Char('/')); // idx points to the first directory
                                                 // after the place path

    const QString path = m_history[m_historyIndex].url.pathOrUrl();
    QString dirName = path.section(QLatin1Char('/'), idx, idx);
    if (dirName.isEmpty()) {
        dirName = QLatin1Char('/');
    }
    do {
        const QString text = spacer + dirName;

        QAction* action = new QAction(text, popup);
        const KUrl currentUrl = buttonUrl(idx);
        if (currentUrl == firstVisibleUrl) {
            popup->addSeparator();
        }
        action->setData(QVariant(currentUrl.prettyUrl()));
        popup->addAction(action);

        ++idx;
        spacer.append("  ");
        dirName = path.section('/', idx, idx);
    } while (!dirName.isEmpty());

    const QPoint pos = q->mapToGlobal(m_dropDownButton->geometry().bottomRight());
    const QAction* activatedAction = popup->exec(pos);
    if (activatedAction != 0) {
        const KUrl url = KUrl(activatedAction->data().toString());
        q->setLocationUrl(url);
    }

    // Delete the menu, unless it has been deleted in its own nested event loop already.
    if (popup) {
        popup->deleteLater();
    }
}
示例#28
0
PushoverSettings::PushoverSettings(Snore::SnorePlugin *plugin, QWidget *parent) :
    Snore::PluginSettingsWidget(plugin, parent),
    m_emailLineEdit(new QLineEdit(this)),
    m_passwordLineEdit(new QLineEdit(this)),
    m_deviceLineEdit(new QLineEdit(this)),
    m_registerButton(new QPushButton(this)),
    m_errorMessageLabel(new QLabel(this))
{
    m_passwordLineEdit->setEchoMode(QLineEdit::Password);
    addRow(tr("Email Address:"), m_emailLineEdit);
    addRow(tr("Password:"******"Device Name:"), m_deviceLineEdit);
    addRow(QString(), m_registerButton);
    addRow(tr("Status"), m_errorMessageLabel);
    addRow(QString(), new QLabel(this));
    addRow(QString(), new QLabel(tr("If you don't have an account yet please register at <a href=\"https://pushover.net\">Pushover.net</a>"), this));

    m_emailLineEdit->setEnabled(false);
    m_passwordLineEdit->setEnabled(false);
    m_deviceLineEdit->setEnabled(false);
    m_registerButton->setEnabled(false);

    QPointer<PushoverClient> pushover = plugin->constHints().value("client").value<QPointer<PushoverClient>>();
    Q_ASSERT_X(pushover, Q_FUNC_INFO, "Failed to retrieve PushoverClient.");

    if (pushover) {

        m_errorMessageLabel->setText(pushover->errorMessage());

        connect(pushover, &PushoverClient::loggedInChanged, this, &PushoverSettings::slotUpdateLoginState);
        connect(pushover, &PushoverClient::error, [this](const QString & message) {
            m_errorMessageLabel->setText(message);
        });

        slotUpdateLoginState(pushover->isLoggedIn());

        connect(m_registerButton, &QPushButton::clicked, [pushover, this]() {
            m_registerButton->setEnabled(false);
            if (pushover->isLoggedIn() != PushoverClient::LoggedIn) {
                pushover->login(m_emailLineEdit->text(), m_passwordLineEdit->text(), m_deviceLineEdit->text());
            } else {
                pushover->logOut();
            }
        });

    }

}
void QgsGeoPackageCollectionItem::deleteGpkg( const QString &path, QPointer<QgsDataItem> parent )
{
  const QString title = QObject::tr( "Delete GeoPackage" );
  // Check if the layer is in the project
  const QgsMapLayer *projectLayer = nullptr;
  const auto mapLayers = QgsProject::instance()->mapLayers();
  for ( auto it = mapLayers.constBegin(); it != mapLayers.constEnd(); ++it )
  {
    const QVariantMap parts = QgsProviderRegistry::instance()->decodeUri( it.value()->dataProvider()->name(), it.value()->source() );
    if ( parts.value( QStringLiteral( "path" ) ).toString() == path )
    {
      projectLayer = it.value();
    }
  }
  if ( ! projectLayer )
  {
    const QString confirmMessage = QObject::tr( "Are you sure you want to delete '%1'?" ).arg( path );

    if ( QMessageBox::question( nullptr, title,
                                confirmMessage,
                                QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) != QMessageBox::Yes )
      return;

    if ( !QFile::remove( path ) )
    {
      QMessageBox::warning( nullptr, title, tr( "Could not delete GeoPackage." ) );
    }
    else
    {
      QMessageBox::information( nullptr, title, tr( "GeoPackage deleted successfully." ) );
      if ( parent )
        parent->refresh();
    }
  }
  else
  {
    QMessageBox::warning( nullptr, title, QObject::tr( "The GeoPackage '%1' cannot be deleted because it is in the current project as '%2',"
                          " remove it from the project and retry." ).arg( path, projectLayer->name() ) );
  }
}
示例#30
0
void TextDocument::drawBackground(QPainter* painter, const QRect& bounds)
{
    if (d.highlights.isEmpty() && d.lowlight == -1)
        return;

    const int margin = qCeil(documentMargin());
    const QAbstractTextDocumentLayout* layout = documentLayout();

    static QPointer<TextLowlight> lowlightFrame = 0;
    if (!lowlightFrame)
        lowlightFrame = new TextLowlight(static_cast<QWidget*>(painter->device()));

    static QPointer<TextHighlight> highlightFrame = 0;
    if (!highlightFrame)
        highlightFrame = new TextHighlight(static_cast<QWidget*>(painter->device()));

    if (d.lowlight != -1) {
        const QAbstractTextDocumentLayout* layout = documentLayout();
        const int margin = qCeil(documentMargin());
        const QTextBlock to = findBlockByNumber(d.lowlight);
        if (to.isValid()) {
            QRect br = layout->blockBoundingRect(to).toAlignedRect();
            br.setTop(0);
            if (bounds.intersects(br)) {
                br.adjust(-margin - 1, 0, margin + 1, 2);
                painter->translate(br.topLeft());
                lowlightFrame->setGeometry(br);
                lowlightFrame->render(painter);
                painter->translate(-br.topLeft());
            }
        }
    }

    foreach (int highlight, d.highlights) {
        QTextBlock block = findBlockByNumber(highlight);
        if (block.isValid()) {
            QRect br = layout->blockBoundingRect(block).toAlignedRect();
            if (bounds.intersects(br)) {
                br.adjust(-margin - 1, 0, margin + 1, 2);
                painter->translate(br.topLeft());
                highlightFrame->setGeometry(br);
                highlightFrame->render(painter);
                painter->translate(-br.topLeft());
            }
        }
    }
}