コード例 #1
0
ファイル: ListView.cpp プロジェクト: mleduque/kwin-tiling
void
ListView::answerReceived(int id, const QList<QByteArray>& answer)
{
    /* We received something, so the sensor is probably ok. */
    sensorError(id, false);

    switch (id)
    {
        case 100: {
            /* We have received the answer to a '?' command that contains
             * the information about the table headers. */
            if (answer.count() != 2)
            {
                kWarning(1215) << "wrong number of lines";
                return;
            }
            KSGRD::SensorTokenizer headers(answer[0], '\t');
            KSGRD::SensorTokenizer colTypes(answer[1], '\t');

            /* add the new columns */
            mModel.clear();
            QStringList translatedHeaders;
            for (uint i = 0; i < headers.count(); i++) {
                translatedHeaders.append( i18nc("heading from daemon", headers[i]) );
            }

            for(uint i =0 ; i < colTypes.count(); i++) {
                ColumnType type = convertColumnType(colTypes[i]);
                mColumnTypes.append(type);
                if (type == Text || type == DiskStat)
                    mModel.addColumnAlignment(Qt::AlignLeft);
                else
                    mModel.addColumnAlignment(Qt::AlignRight);
            }

            mModel.setHorizontalHeaderLabels(translatedHeaders);
            //If we have some header settings to restore, we can do so now
            if(!mHeaderSettings.isEmpty()) {
                mView->header()->restoreState(mHeaderSettings);
                mModel.sort( mView->header()->sortIndicatorSection(), mView->header()->sortIndicatorOrder() );
            }
            break;
        }
        case 19: {
            for (int i = 0; i < answer.count(); i++) {
                KSGRD::SensorTokenizer records(answer[i], '\t');
                for (uint j = 0; j < records.count() && j < mColumnTypes.count(); j++) {
                    QStandardItem *item = new QStandardItem();
                    item->setEditable(false);
                    switch( mColumnTypes[j] ) {
                      case Int:
                        item->setData(records[j].toLongLong(), Qt::UserRole);
                        item->setText(records[j]);
                        break;
                      case Percentage:
                        item->setData(records[j].toInt(), Qt::UserRole);
                        item->setText(records[j] + "%");
                        break;
                      case Float:
                        item->setData(records[j].toFloat(), Qt::DisplayRole);
                        item->setData(records[j].toFloat(), Qt::UserRole);
                        break;
                      case Time:
                        item->setData(QTime::fromString(records[j]), Qt::DisplayRole);
                        item->setData(QTime::fromString(records[j]), Qt::UserRole);
                        break;
                      case KByte: {
                        item->setData(records[j].toInt(), Qt::UserRole);
                        item->setText(formatByteSize(records[j].toLongLong(), mUnits));
                        break;
                      }
                      case DiskStat:
                      case Text:
                      default:
                        item->setText(records[j]);
                        item->setData(records[j], Qt::UserRole);
                    }
                    mModel.setItem(i, j, item);
                }
            }
            mModel.setRowCount(answer.count());
            mModel.sort( mView->header()->sortIndicatorSection(), mView->header()->sortIndicatorOrder() );
            break;
        }
    }
}
コード例 #2
0
void PreferencesDialog::InitChanInfo()
{
    QHash<MachineType, int> toprows;

    chanModel->clear();
    toplevel.clear();
    toprows.clear();
    QStringList headers;
    headers.append(tr("Name"));
    headers.append(tr("Color"));
    headers.append(tr("Overview"));
    headers.append(tr("Flag Type"));
    headers.append(tr("Label"));
    headers.append(tr("Details"));
    chanModel->setHorizontalHeaderLabels(headers);
    ui->chanView->setColumnWidth(0, 200);
    ui->chanView->setColumnWidth(1, 40);
    ui->chanView->setColumnWidth(2, 60);
    ui->chanView->setColumnWidth(3, 100);
    ui->chanView->setColumnWidth(4, 100);
    ui->chanView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->chanView->setSelectionBehavior(QAbstractItemView::SelectItems);

    chanModel->setColumnCount(6);

    QStandardItem *hdr = nullptr;

    QMap<MachineType, QString> Section;

    Section[MT_CPAP] = tr("CPAP Events");
    Section[MT_OXIMETER] = tr("Oximeter Events");
    Section[MT_POSITION] = tr("Positional Events");
    Section[MT_SLEEPSTAGE] = tr("Sleep Stage Events");
    Section[MT_UNCATEGORIZED] = tr("Unknown Events");

    QMap<MachineType, QString>::iterator it;

    QHash<QString, schema::Channel *>::iterator ci;

    for (it = Section.begin(); it != Section.end(); ++it) {
        toplevel[it.key()] = hdr = new QStandardItem(it.value());
        hdr->setEditable(false);
        QList<QStandardItem *> list;
        list.append(hdr);
        for (int i=0; i<5; i++) {
            QStandardItem *it = new QStandardItem();
            it->setEnabled(false);
            list.append(it);
        }
        chanModel->appendRow(list);
    }

    ui->chanView->setAlternatingRowColors(true);

    // ui->graphView->setFirstColumnSpanned(0,daily->index(),true); // Crashes on windows.. Why do I need this again?


    ComboBoxDelegate * combobox = new ComboBoxDelegate(ui->waveView);

    ui->chanView->setItemDelegateForColumn(3,combobox);

    int row = 0;
    for (ci = schema::channel.names.begin(); ci != schema::channel.names.end(); ci++) {
        schema::Channel * chan = ci.value();
        if ((chan->type() == schema::DATA) || (chan->type() == schema::SETTING) || chan->type() == schema::WAVEFORM) continue;

        QList<QStandardItem *> items;
        QStandardItem *it = new QStandardItem(chan->fullname());
        it->setCheckable(true);
        it->setCheckState(chan->enabled() ? Qt::Checked : Qt::Unchecked);
        it->setEditable(true);
        it->setData(chan->id(), Qt::UserRole);

        // Dear translators: %1 is a unique ascii english string used to indentify channels in the code, I'd like feedback on how this goes..
        // It's here in case users mess up which field is which.. it will always show the Channel Code underneath in the tooltip.
        it->setToolTip(tr("Double click to change the descriptive name the '%1' channel.").arg(chan->code()));
        items.push_back(it);


        it = new QStandardItem();
        it->setBackground(QBrush(chan->defaultColor()));
        it->setEditable(false);
        it->setData(chan->defaultColor().rgba(), Qt::UserRole);
        it->setToolTip(tr("Double click to change the default color for this channel plot/flag/data."));
        it->setSelectable(false);
        items.push_back(it);

        it = new QStandardItem(QString());
        it->setToolTip(tr("Whether this flag has a dedicated overview chart."));
        it->setCheckable(true);
        it->setCheckState(chan->showInOverview() ? Qt::Checked : Qt::Unchecked);
        it->setTextAlignment(Qt::AlignCenter);
        it->setData(chan->id(), Qt::UserRole);
        items.push_back(it);

        schema::ChanType type = chan->type();

        it = new QStandardItem(channeltype[type]);
        it->setToolTip(tr("Here you can change the type of flag shown for this event"));
        it->setEditable(type != schema::UNKNOWN);
        items.push_back(it);

        it = new QStandardItem(chan->label());
        it->setToolTip(tr("This is the short-form label to indicate this channel on screen."));

        it->setEditable(true);
        items.push_back(it);

        it = new QStandardItem(chan->description());
        it->setToolTip(tr("This is a description of what this channel does."));

        it->setEditable(true);
        items.push_back(it);

        MachineType mt = chan->machtype();
        if (chan->type() == schema::UNKNOWN) mt = MT_UNCATEGORIZED;
        row = toprows[mt]++;
        toplevel[mt]->insertRow(row, items);
    }


    for(QHash<MachineType, QStandardItem *>::iterator i = toplevel.begin(); i != toplevel.end(); ++i) {
        if (i.value()->rowCount() == 0) {
            chanModel->removeRow(i.value()->row());
        }
    }

    ui->chanView->expandAll();
    ui->chanView->setSortingEnabled(true);
}
コード例 #3
0
AddRecipients::AddRecipients(QLineEdit & listRecipients,QWidget *parent) :
    QDialog(parent)
{
    setFixedWidth(300);
    setWindowTitle("Ajouter un destinataire");

    currentListRecipients = &listRecipients;

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("database.db");

    if (!db.open())
    {
        qDebug() << "Impossible de se connecter à la base de données." << endl;
        return;
    }

    listView_users = new QListView();
    listView_users->setEditTriggers(0);

    QSqlQuery query;
    query.exec("SELECT * FROM Contacts");

    modelListUsers = new QStandardItemModel();

    int index = 0;
    while(query.next())
    {
        User user(query.value(1).toInt(),QString(query.value(2).toString()));

        QStandardItem *item = new QStandardItem();
        item->setText(user.address());

        QVariant data;
        data.setValue(user);
        item->setData(data);

        modelListUsers->setItem(index,item);
        index++;
    }

    listView_users->setModel(modelListUsers);

    QVBoxLayout *layout_add_users = new QVBoxLayout();
    layout_add_users->addWidget(listView_users);

    btn_add_user = new QPushButton("Ajouter le contact");

    QVBoxLayout *layout_btn_add_users = new QVBoxLayout();
    layout_btn_add_users->addWidget(btn_add_user);

    list_users = new QGroupBox("Contacts");
    form_list_users = new QFormLayout();
    form_list_users->addRow("Liste des contacts : ", listView_users);
    form_list_users->addRow("", layout_btn_add_users);

    list_users->setLayout(form_list_users);

    QVBoxLayout *layout_main = new QVBoxLayout;
    layout_main->addWidget(list_users);

    setLayout(layout_main);

    connect(btn_add_user, SIGNAL(clicked()), this, SLOT(addUser()));
    show();
}
コード例 #4
0
void PodcastDiscoveryModel::LazyLoadImage(const QUrl& url,
                                          const QModelIndex& index) {
  QStandardItem* item = itemFromIndex(index);
  item->setData(true, Role_StartedLoadingImage);
  icon_loader_->LoadIcon(url.toString(), QString(), item);
}
コード例 #5
0
ファイル: resultstree.cpp プロジェクト: gansb/cppcheck
void ResultsTree::AddErrorItem(const ErrorItem &item)
{
    if (item.files.isEmpty()) {
        return;
    }

    QString realfile = StripPath(item.files[0], false);

    if (realfile.isEmpty()) {
        realfile = tr("Undefined file");
    }

    bool hide = !mShowSeverities.isShown(item.severity);
    //bool hide = !mShowTypes[SeverityToShowType(item.severity)];

    //If specified, filter on summary, message, filename, and id
    if (!hide && !mFilter.isEmpty()) {
        if (!item.summary.contains(mFilter, Qt::CaseInsensitive) &&
            !item.message.contains(mFilter, Qt::CaseInsensitive) &&
            !item.file.contains(mFilter, Qt::CaseInsensitive) &&
            !item.errorId.contains(mFilter, Qt::CaseInsensitive)) {
            hide = true;
        }
    }

    //if there is at least one error that is not hidden, we have a visible error
    if (!hide) {
        mVisibleErrors = true;
    }

    ErrorLine line;
    line.file = realfile;
    line.errorId = item.errorId;
    line.inconclusive = item.inconclusive;
    line.line = item.lines[0];
    line.summary = item.summary;
    line.message = item.message;
    line.severity = item.severity;
    //Create the base item for the error and ensure it has a proper
    //file item as a parent
    QStandardItem *stditem = AddBacktraceFiles(EnsureFileItem(line.file, hide),
                             line,
                             hide,
                             SeverityToIcon(line.severity));

    if (!stditem)
        return;

    //Add user data to that item
    QMap<QString, QVariant> data;
    data["hide"] = false;
    data["severity"]  = ShowTypes::SeverityToShowType(item.severity);
    data["summary"] = item.summary;
    data["message"]  = item.message;
    data["file"]  = item.files[0];
    data["line"]  = item.lines[0];
    data["id"]  = item.errorId;
    data["inconclusive"] = item.inconclusive;
    stditem->setData(QVariant(data));

    //Add backtrace files as children
    for (int i = 1; i < item.files.size(); i++) {
        line.file = StripPath(item.files[i], false);
        line.line = item.lines[i];
        QStandardItem *child_item;
        child_item = AddBacktraceFiles(stditem,
                                       line,
                                       hide,
                                       ":images/go-down.png");

        //Add user data to that item
        QMap<QString, QVariant> child_data;
        child_data["severity"]  = ShowTypes::SeverityToShowType(line.severity);
        child_data["summary"] = line.summary;
        child_data["message"]  = line.message;
        child_data["file"]  = item.files[i];
        child_data["line"]  = line.line;
        child_data["id"]  = line.errorId;
        child_data["inconclusive"] = line.inconclusive;
        child_item->setData(QVariant(child_data));
    }

    //TODO just hide/show current error and it's file
    //since this does a lot of unnecessary work
    if (!hide) {
        ShowFileItem(realfile);
    }
}
コード例 #6
0
void QgsGrassTools::addModules( QTreeWidgetItem *parent, QDomElement &element )
{
  QDomNode n = element.firstChild();

  QTreeWidgetItem *item;
  QTreeWidgetItem *lastItem = 0;
  while ( !n.isNull() )
  {
    QDomElement e = n.toElement();
    if ( !e.isNull() )
    {
// QgsDebugMsg(QString("tag = %1").arg(e.tagName()));

      if ( e.tagName() == "section" && e.tagName() == "grass" )
      {
        QgsDebugMsg( QString( "Unknown tag: %1" ).arg( e.tagName() ) );
        continue;
      }

      if ( parent )
      {
        item = new QTreeWidgetItem( parent, lastItem );
      }
      else
      {
        item = new QTreeWidgetItem( mModulesTree, lastItem );
      }

      if ( e.tagName() == "section" )
      {
        QString label = QApplication::translate( "grasslabel", e.attribute( "label" ).toUtf8() );
        QgsDebugMsg( QString( "label = %1" ).arg( label ) );
        item->setText( 0, label );
        item->setExpanded( false );

        addModules( item, e );

        lastItem = item;
      }
      else if ( e.tagName() == "grass" )
      { // GRASS module
        QString name = e.attribute( "name" );
        QgsDebugMsg( QString( "name = %1" ).arg( name ) );

        QString path = QgsApplication::pkgDataPath() + "/grass/modules/" + name;
        QString label = QgsGrassModule::label( path );
        QPixmap pixmap = QgsGrassModule::pixmap( path, 32 );

        item->setText( 0, name + " - " + label );
        item->setIcon( 0, QIcon( pixmap ) );
        item->setText( 1, name );
        lastItem = item;


        //
        // Experimental work by Tim - add this item to our list model
        //
        QStandardItem * mypDetailItem = new QStandardItem( name + "\n" + label );
        mypDetailItem->setData( name, Qt::UserRole + 1 ); //for calling runModule later
        QString mySearchText = name + " - " + label;
        mypDetailItem->setData( mySearchText, Qt::UserRole + 2 ); //for filtering later
        mypDetailItem->setData( pixmap, Qt::DecorationRole );
        mypDetailItem->setCheckable( false );
        mypDetailItem->setEditable( false );
        // setData in the delegate with a variantised QgsDetailedItemData
        QgsDetailedItemData myData;
        myData.setTitle( name );
        myData.setDetail( label );
        myData.setIcon( pixmap );
        myData.setCheckable( false );
        myData.setRenderAsWidget( false );
        QVariant myVariant = qVariantFromValue( myData );
        mypDetailItem->setData( myVariant, Qt::UserRole );
        mModelTools->appendRow( mypDetailItem );
        //
        // End of experimental work by Tim
        //
      }
    }
    n = n.nextSibling();
  }
}
コード例 #7
0
bool AMDatamanAppControllerForActions2::startupCreateUserInterface()
{
	AMErrorMon::information(this, AMDATAMANAPPCONTROLLER_STARTUP_MESSAGES, "Acquaman Startup: Populating User Interface");
	qApp->processEvents();
	settingsMasterView_ = 0;
	issueSubmissionView_ = 0;
	bottomBar_ = new AMBottomBar();
	// These buttons are never used.  Hiding them.
	bottomBar_->fullScreenButton->hide();
	bottomBar_->adjustScanFinishButton->hide();
	bottomBar_->restartScanButton->hide();
	mw_->addBottomWidget(bottomBar_);
	connect(bottomBar_, SIGNAL(addButtonClicked()), this, SLOT(onAddButtonClicked()));
	connect(bottomBar_, SIGNAL(pauseScanIssued()), this, SIGNAL(pauseScanIssued()));
	connect(bottomBar_, SIGNAL(resumeScanIssued()), this, SIGNAL(resumeScanIssued()));
	connect(bottomBar_, SIGNAL(stopScanIssued()), this, SIGNAL(stopScanIssued()));

	// Create panes in the main window:
	////////////////////////////////////

	// A heading for the scan editors
	scanEditorsParentItem_ = mw_->windowPaneModel()->headingItem("Open Scans");


	// Make a dataview widget and add it under two links/headings: "Runs" and "Experiments". See AMMainWindowModel for more information.
	////////////////////////////////////
	dataView_ = new AMDataViewWithActionButtons();
	dataView_->setWindowTitle("Data");

	QStandardItem* dataViewItem = new QStandardItem();
	dataViewItem->setData(qVariantFromValue((QWidget*)dataView_), AM::WidgetRole);
	dataViewItem->setFlags(Qt::ItemIsEnabled);	// enabled, but should not be selectable
	QFont font = QFont("Lucida Grande", 10, QFont::Bold);
	font.setCapitalization(QFont::AllUppercase);
	dataViewItem->setFont(font);
	dataViewItem->setData(QBrush(QColor::fromRgb(100, 109, 125)), Qt::ForegroundRole);
	dataViewItem->setData(true, AMWindowPaneModel::DockStateRole);

	mw_->windowPaneModel()->appendRow(dataViewItem);

	runsParentItem_ = new QStandardItem(QIcon(":/22x22/view_calendar_upcoming_days.png"), "Runs");
	mw_->windowPaneModel()->initAliasItem(runsParentItem_, dataViewItem, "Runs", -1);
	dataViewItem->appendRow(runsParentItem_);
	experimentsParentItem_ = new QStandardItem(QIcon(":/applications-science.png"), "Experiments");
	mw_->windowPaneModel()->initAliasItem(experimentsParentItem_, dataViewItem, "Experiments", -1);
	dataViewItem->appendRow(experimentsParentItem_);

	// Hook into the sidebar and add Run and Experiment links below these headings.
	runExperimentInsert_ = new AMRunExperimentInsert(AMDatabase::database("user"), runsParentItem_, experimentsParentItem_, this);
	connect(runExperimentInsert_, SIGNAL(newExperimentAdded(QModelIndex)), this, SLOT(onNewExperimentAdded(QModelIndex)));

	// connect the activated signal from the dataview to our own slot
	connect(dataView_, SIGNAL(selectionActivated(QList<QUrl>)), this, SLOT(onDataViewItemsActivated(QList<QUrl>)));
	connect(dataView_, SIGNAL(selectionActivatedSeparateWindows(QList<QUrl>)), this, SLOT(onDataViewItemsActivatedSeparateWindows(QList<QUrl>)));
	connect(dataView_, SIGNAL(selectionExported(QList<QUrl>)), this, SLOT(onDataViewItemsExported(QList<QUrl>)));
	connect(dataView_, SIGNAL(launchScanConfigurationsFromDb(QList<QUrl>)), this, SLOT(onLaunchScanConfigurationsFromDb(QList<QUrl>)));
	connect(dataView_, SIGNAL(fixCDF(QUrl)), this, SLOT(fixCDF(QUrl)));

	// When 'alias' links are clicked in the main window sidebar, we might need to notify some widgets of the details
	connect(mw_, SIGNAL(aliasItemActivated(QWidget*,QString,QVariant)), this, SLOT(onMainWindowAliasItemActivated(QWidget*,QString,QVariant)));
	/////////////////////////

	// Make connections:
	//////////////////////////////

	connect(mw_, SIGNAL(currentPaneChanged(QWidget*)), this, SLOT(onCurrentPaneChanged(QWidget*)));

	// show main window
	mw_->show();

	return true;
}
コード例 #8
0
QStandardItem *FlagColumn::build_cell(Dwarf *d) {
    QStandardItem *item = init_cell(d);

    item->setData(CT_FLAGS, DwarfModel::DR_COL_TYPE);
    item->setData(0,DwarfModel::DR_STATE); //default

    QString info_msg = "";
    QString info_col_name = "";

    short rating = 0;
    if(d->get_flag_value(m_bit_pos))
        rating = 1;
    //check to fix butchering pets. currently this will cause the butchered parts to still be recognized as a pet
    //and they'll put them into a burial recepticle, but won't use them as a food source
    ViewColumn::CELL_STATE state  = STATE_TOGGLE;
    if(m_bit_pos == FLAG_BUTCHER){
        if(d->is_pet()){
            info_msg = tr("<b>Pets cannot be slaughtered!</b>");
            state = STATE_DISABLED;
        }else if(!d->get_caste() || !d->get_caste()->flags().has_flag(BUTCHERABLE)){
            info_msg = tr("<b>This caste cannot be slaughtered!</b>");
            state = STATE_DISABLED;
        }else if(rating == 1){
            info_msg = tr("<b>This creature has been marked for slaughter.</b>");
            state = STATE_PENDING;
        }else if(d->trained_level() >= Dwarf::unknown_trained){
            info_msg = tr("<b>Captured wild animals cannot be butchered!</b>");
            state = STATE_DISABLED;
        }else{
            state = STATE_TOGGLE;
        }
    }else if(m_bit_pos == FLAG_GELD){
        if(d->get_gender() != Dwarf::SEX_M){
            info_msg = tr("<b>Only males can be gelded!</b>");
            state = STATE_DISABLED;
        }else if(d->has_health_issue(eHealth::HI_GELDED,0)){
            info_msg = tr("<b>This creature has already been gelded!</b>");
            state = STATE_ACTIVE;
        }else if(rating == 1){
            info_msg = tr("<b>This creature has been marked for gelding.</b>");
            state = STATE_PENDING;
        }else if(!d->get_caste()->is_geldable()){ //check last as it's the most expensive
            info_msg = tr("<b>This caste is not geldable!</b>");
            state = STATE_DISABLED;
        }else{
            state = STATE_TOGGLE;
        }
    }

    item->setData(state,DwarfModel::DR_STATE);
    info_col_name = get_state_color(state).name();//item->data(Qt::BackgroundColorRole).value<QColor>().name();

    item->setData(rating, DwarfModel::DR_SORT_VALUE);
    item->setData(m_bit_pos, DwarfModel::DR_OTHER_ID);
    item->setData(m_set->name(), DwarfModel::DR_SET_NAME);

    QString tooltip = QString("<center><h3>%1</h3>%2</center>%3")
            .arg(m_title)
            .arg(QString("<font color=%1>%2</font>").arg(info_col_name).arg(info_msg))
            .arg(tooltip_name_footer(d));
    item->setToolTip(tooltip);

    return item;
}
コード例 #9
0
ファイル: gmapdlg.cpp プロジェクト: alexbirkett/GPSBabel
//------------------------------------------------------------------------
GMapDialog::GMapDialog(QWidget *parent, const QString &gpxFileName, QPlainTextEdit *te): QDialog(parent)
{
    ui.setupUi(this);
    this->setWindowTitle(QString(appName) + " " + QString("Google Maps"));
    gpx.read(gpxFileName);

    mapWidget = new Map(this, gpx, te);
    QHBoxLayout *lay = new QHBoxLayout(ui.frame);
    lay->setContentsMargins(0, 0, 0, 0);
    lay->addWidget(mapWidget);

    model = new QStandardItemModel(this);

    wptItem = new StandardItem(tr("Waypoints"));
    wptItem->setCheckable(true);
    wptItem->setCheckState(Qt::Checked);
    model->appendRow(wptItem);
    for (int i=0; i<gpx.getWaypoints().size(); i++) {
        GpxWaypoint &wpt = gpx.getWaypoints()[i];
        QStandardItem *it = new StandardItem(wpt.getName());
        wptItem->appendRow(it);
        it->setCheckable(true);
        it->setCheckState(Qt::Checked);
        it->setData(qVariantFromValue((void *)&wpt));
        appendWaypointInfo(it, wpt);
        wptList << it;
    }

    trkItem = new StandardItem(tr("Tracks"));
    trkItem->setCheckable(true);
    trkItem->setCheckState(Qt::Checked);
    model->appendRow(trkItem);
    for (int i=0; i<gpx.getTracks().size(); i++) {
        GpxTrack &trk = gpx.getTracks()[i];
        QStandardItem *it = new StandardItem(trk.getName());
        trkItem->appendRow(it);
        it->setCheckable(true);
        it->setCheckState(Qt::Checked);
        it->setData(qVariantFromValue((void *)&trk));
        appendTrackInfo(it, trk);
        trkList << it;
    }

    rteItem = new StandardItem(tr("Routes"));
    rteItem->setCheckable(true);
    rteItem->setCheckState(Qt::Checked);
    model->appendRow(rteItem);
    for (int i=0; i<gpx.getRoutes().size(); i++) {
        GpxRoute &rte = gpx.getRoutes()[i];
        QStandardItem *it = new StandardItem(rte.getName());
        rteItem->appendRow(it);
        it->setCheckable(true);
        it->setCheckState(Qt::Checked);
        it->setData(qVariantFromValue((void *)&rte));
        appendRouteInfo(it, rte);
        rteList << it;
    }

    ui.treeView->header()->hide();
    ui.treeView->setModel(model);
    ui.treeView->setExpandsOnDoubleClick(false);
    connect(model, SIGNAL(itemChanged(QStandardItem *)),
            this,  SLOT(itemChangedX(QStandardItem *)));
    connect(mapWidget, SIGNAL(waypointClicked(int)), this, SLOT(waypointClickedX(int)));
    connect(mapWidget, SIGNAL(routeClicked(int)), this, SLOT(routeClickedX(int)));
    connect(mapWidget, SIGNAL(trackClicked(int)), this, SLOT(trackClickedX(int)));
    connect(ui.treeView, SIGNAL(doubleClicked(const QModelIndex &)),
            this, SLOT(treeDoubleClicked(const QModelIndex&)));
    connect(ui.treeView->selectionModel(), SIGNAL(selectionChanged (const QItemSelection &,  const QItemSelection &)),
            this, SLOT(selectionChangedX(const QItemSelection &,  const QItemSelection &)));

    ui.treeView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui.treeView, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(showContextMenu(const QPoint &)));

    connect(ui.copyButton, SIGNAL(clicked()), this, SLOT(copyButtonClickedX()));

    ui.copyButton->hide(); // Hide for now, not working

}
コード例 #10
0
QStandardItem* ToolBarDialog::createEntry(const QString &identifier)
{
	QStandardItem *item = new QStandardItem();
	item->setData(identifier, Qt::UserRole);
	item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemNeverHasChildren);

	if (identifier == QLatin1String("separator"))
	{
		item->setText(tr("--- separator ---"));
	}
	else if (identifier == QLatin1String("spacer"))
	{
		item->setText(tr("--- spacer ---"));
	}
	else if (identifier == QLatin1String("AddressWidget"))
	{
		item->setText(tr("Address Field"));
	}
	else if (identifier == QLatin1String("ClosedWindowsWidget"))
	{
		item->setText(tr("List of Closed Windows and Tabs"));
	}
	else if (identifier == QLatin1String("MenuBarWidget"))
	{
		item->setText(tr("Menu Bar"));
	}
	else if (identifier == QLatin1String("MenuButtonWidget"))
	{
		item->setText(tr("Menu Button"));
	}
	else if (identifier == QLatin1String("PanelChooserWidget"))
	{
		item->setText(tr("Sidebar Panel Chooser"));
	}
	else if (identifier == QLatin1String("SearchWidget"))
	{
		item->setText(tr("Search Field"));
	}
	else if (identifier == QLatin1String("StatusMessageWidget"))
	{
		item->setText(tr("Status Message Field"));
	}
	else if (identifier == QLatin1String("TabBarWidget"))
	{
		item->setText(tr("Tab Bar"));
	}
	else if (identifier == QLatin1String("ZoomWidget"))
	{
		item->setText(tr("Zoom Slider"));
	}
	else if (identifier.startsWith(QLatin1String("bookmarks:")))
	{
		BookmarksItem *bookmark = (identifier.startsWith(QLatin1String("bookmarks:/")) ? BookmarksManager::getModel()->getItem(identifier.mid(11)) : BookmarksManager::getBookmark(identifier.mid(10).toULongLong()));

		if (bookmark)
		{
			item->setText(bookmark->data(BookmarksModel::TitleRole).isValid() ? bookmark->data(BookmarksModel::TitleRole).toString() : tr("(Untitled)"));
			item->setIcon(bookmark->data(Qt::DecorationRole).value<QIcon>());
		}
		else
		{
			item->setText(tr("Invalid Bookmark"));
		}
	}
	else if (identifier.endsWith(QLatin1String("Action")))
	{
		const int actionIdentifier = ActionsManager::getActionIdentifier(identifier.left(identifier.length() - 6));

		if (actionIdentifier < 0)
		{
			item->setText(tr("Invalid Entry"));
		}
		else
		{
			const ActionDefinition definition = ActionsManager::getActionDefinition(actionIdentifier);

			item->setText(QCoreApplication::translate("actions", (definition.description.isEmpty() ? definition.text : definition.description).toUtf8().constData()));
			item->setIcon(definition.icon);
		}
	}
	else
	{
		item->setText(tr("Invalid Entry"));
	}

	return item;
}
コード例 #11
0
ファイル: Load.cpp プロジェクト: FantasyNJ/BiliLocal-OSX
Load::Load(QObject *parent) : QObject(parent), d_ptr(new LoadPrivate(this))
{
	Q_D(Load);
	ins = this;
	setObjectName("Load");

	auto avProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString i = task.code.mid(2, sharp - 2);
			QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1);
			QString url("http://www.%1/video/av%2/");
			url = url.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
			if (!p.isEmpty()){
				url += QString("index_%1.html").arg(p);
			}
			forward(QNetworkRequest(url), Page);
			break;
		}
		case Page:
		{
			d->model->clear();
			QString api, id, video(reply->readAll());
			int part = video.indexOf("<select");
			if (part != -1 && sharp == -1){
				QRegularExpression r("(?<=>).*?(?=</option>)");
				QStringRef list(&video, part, video.indexOf("</select>", part) - part);
				QRegularExpressionMatchIterator i = r.globalMatch(list);
				api = "http://www.%1/video/%2/index_%3.html";
				api = api.arg(Utils::customUrl(Utils::Bilibili));
				while (i.hasNext()){
					int index = d->model->rowCount() + 1;
					QStandardItem *item = new QStandardItem;
					item->setData(QUrl(api.arg(task.code).arg(index)), UrlRole);
					item->setData((task.code + "#%1").arg(index), StrRole);
					item->setData(Page, NxtRole);
					item->setData(Utils::decodeXml(i.next().captured()), Qt::EditRole);
					d->model->appendRow(item);
				}
			}
			if (d->model->rowCount() > 0){
				emit stateChanged(task.state = Part);
			}
			else{
				QRegularExpression r = QRegularExpression("cid[=\":]*\\d+", QRegularExpression::CaseInsensitiveOption);
				QRegularExpressionMatchIterator i = r.globalMatch(video);
				while (i.hasNext()){
					QString m = i.next().captured();
					m = QRegularExpression("\\d+").match(m).captured();
					if (id.isEmpty()){
						id = m;
					}
					else if (id != m){
						id.clear();
						break;
					}
				}
				if (!id.isEmpty()){
					api = "http://comment.%1/%2.xml";
					api = api.arg(Utils::customUrl(Utils::Bilibili));
					forward(QNetworkRequest(api.arg(id)), File);
				}
                else{
                    emit stateChanged(203);
                    qDebug() << "Fail to load danmaku, try biliApi";
                    dequeue();
                }
            }
			break;
		}
		case File:
		{
			dumpDanmaku(reply->readAll(), Utils::Bilibili, false);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	auto avRegular = [](QString &code){
		code.remove(QRegularExpression("/index(?=_\\d+\\.html)"));
		QRegularExpression r("a(v(\\d+([#_])?(\\d+)?)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return getRegular(r)(code);
	};
	d->pool.append({ avRegular, 0, avProcess });

	auto bbProcess = [this, avProcess](QNetworkReply *reply) {
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state) {
		case None:
		{
			QString i = task.code.mid(2);
			QString u = "http://www.%1/bangumi/i/%2/";
			u = u.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
			forward(QNetworkRequest(u), Page);
			break;
		}
		case Page:
		{
			d->model->clear();
			QString page(reply->readAll());
			QStringList list = page.split("<li data-index");

			if (list.size() < 2) {
				emit stateChanged(task.state = None);
				dequeue();
				break;
			}

			list.removeFirst();
			QListIterator<QString> iter(list);
			iter.toBack();
			while (iter.hasPrevious()) {
				QRegularExpression r;
				const QString &i = iter.previous();
				r.setPattern("(?<=href=\")[^\"]+");
				QString c = r.match(i).captured();
				fixCode(c);
				r.setPattern("(?<=<span>).+(?=</span>)");
				QString t = Utils::decodeXml(r.match(i).captured());

				QStandardItem *item = new QStandardItem;
				item->setData(c, StrRole);
				item->setData(None, NxtRole);
				item->setData(t, Qt::EditRole);
				d->model->appendRow(item);
			}
			emit stateChanged(task.state = Part);
		}
		}
	};

	auto bbRegular = [](QString &code) {
		code.replace(QRegularExpression("bangumi/i/(?=\\d+)"), "bb");
		QRegularExpression r("b(b(\\d+)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return getRegular(r)(code);
	};
	d->pool.append({ bbRegular, 0, bbProcess });

	auto acProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString i = task.code.mid(2, sharp - 2);
			QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1);
			QString url("http://www.%1/v/ac%2");
			url = url.arg(Utils::customUrl(Utils::AcFun)).arg(i);
			if (!p.isEmpty()){
				url += QString("_%1").arg(p);
			}
			forward(QNetworkRequest(url), Page);
			break;;
		}
		case Page:
		{
			d->model->clear();
			QRegularExpressionMatchIterator match = QRegularExpression("data-vid.*?</a>").globalMatch(reply->readAll());
			while (match.hasNext()){
				QStandardItem *item = new QStandardItem;
				QString part = match.next().captured();
				QRegularExpression r;
				r.setPattern("(?<=>)[^>]+?(?=</a>)");
				item->setData(Utils::decodeXml(r.match(part).captured()), Qt::EditRole);
				r.setPattern("(?<=data-vid=\").+?(?=\")");
				QString next("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1");
				next = next.arg(Utils::customUrl(Utils::AcFun)).arg(r.match(part).captured());
				item->setData(next, UrlRole);
				item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole);
				item->setData(File, NxtRole);
				d->model->appendRow(item);
			}
			if (sharp == -1 && d->model->rowCount() >= 2){
				emit stateChanged(task.state = Part);
			}
			else{
				int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1;
				if (i >= 0 && i < d->model->rowCount()){
					forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File);
				}
				else{
					emit stateChanged(203);
					dequeue();
				}
			}
			break;
		}
		case File:
		{
			QByteArray data = reply->readAll();
			if (data != "[[],[],[]]"){
				QNetworkRequest &request = task.request;
				QUrl url = request.url();
				int page = QUrlQuery(url).queryItemValue("pageNo").toInt();
				url.setQuery(QString());
				request.setUrl(url);
				dumpDanmaku(data, Utils::AcFun, false);
				QUrlQuery query;
				query.addQueryItem("pageSize", "1000");
				query.addQueryItem("pageNo", QString::number(page + 1));
				url.setQuery(query);
				request.setUrl(url);
				forward(request, File);
			}
			else{
				emit stateChanged(task.state = None);
				dequeue();
			}
			break;
		}
		}
	};
	auto acRegular = getRegular(QRegularExpression("a(c(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption));
	d->pool.append({ acRegular, 0, acProcess });

	auto abProcess = [this, acProcess](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString url("http://www.%1/bangumi/video/page?bangumiId=%2&pageSize=30&pageNo=%3&order=2");
			url = url.arg(Utils::customUrl(Utils::AcFun)).arg(task.code.mid(2, sharp - 2));
			url = url.arg(sharp == -1 ? 1 : (task.code.mid(sharp + 1).toInt() - 1) / 30 + 1);
			forward(QNetworkRequest(url), Page);
			break;
		}
		case Page:
		{
			if (sharp != -1){
				QJsonObject data = QJsonDocument::fromJson(reply->readAll()).object()["data"].toObject();
				int i = task.code.mid(sharp + 1).toInt();
				if (i > 0){
					i = (i - 1) % 30;
				}
				else{
					i = data["totalCount"].toInt();
					if (i > 30){
						task.code = task.code.left(sharp) + QString("#%1").arg(i);
						task.state = None;
						task.processer->process(nullptr);
						break;
					}
				}
				QJsonArray list = data["list"].toArray();
				if (i < 0 || i >= list.size()){
					emit stateChanged(203);
					dequeue();
					break;
				}
				QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1");
				head = head.arg(Utils::customUrl(Utils::AcFun));
				head = head.arg(list[i].toObject()["danmakuId"].toString());
				forward(QNetworkRequest(head), File);
				break;
			}
			else{
				d->model->clear();
			}
		}
		case Part:
		{
			QJsonObject info = QJsonDocument::fromJson(reply->readAll()).object();
			if (!info["success"].toBool() && d->model->rowCount() == 0){
				emit stateChanged(info["status"].toInt());
				dequeue();
			}
			QJsonObject data = info["data"].toObject();
			for (const QJsonValue &value : data["list"].toArray()){
				QStandardItem *item = new QStandardItem;
				QJsonObject data = value.toObject();
				item->setData(data["title"].toString(), Qt::EditRole);
				QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1");
				head = head.arg(Utils::customUrl(Utils::AcFun)).arg(data["danmakuId"].toString());
				item->setData(head, UrlRole);
				item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole);
				item->setData(File, NxtRole);
				d->model->appendRow(item);
			}
			if (task.state != Part){
				emit stateChanged(task.state = Part);
			}
			if (data["pageNo"].toInt() < data["totalPage"].toInt()){
				QUrl url = reply->request().url();
				auto arg = QUrlQuery(url).queryItems();
				for (auto &p : arg){
					if (p.first == "pageNo"){
						p.second = QString::number(p.second.toInt() + 1);
						break;
					}
				}
				QUrlQuery query;
				query.setQueryItems(arg);
				url.setQuery(query);
				d->remain.insert(d->manager.get(QNetworkRequest(url)));
			}
			break;
		}
		case File:
		{
			acProcess(reply);
			break;
		}
		}
	};
	auto abRegular = getRegular(QRegularExpression("a(b(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption));
	d->pool.append({ abRegular, 0, abProcess });

	auto ccProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString i = task.code.mid(2, sharp - 2);
			QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1);
			QString url("http://www.%1/play/h%2/");
			url = url.arg(Utils::customUrl(Utils::TuCao)).arg(i);
			if (!p.isEmpty()){
				url += QString("#%1").arg(p);
			}
			forward(QNetworkRequest(url), Page);
			break;
		}
		case Page:
		{
			QString page = reply->readAll();
			d->model->clear();
			QRegularExpressionMatch m;
			QRegularExpression r("(?<=<li>)[^<]*(?=</li>)");
			m = r.match(page, page.indexOf("<ul id=\"player_code\""));
			QStringList list = m.captured().split("**");
			m = r.match(page, m.capturedEnd());
			QString code = m.captured();
			for (const QString &iter : list){
				QStandardItem *item = new QStandardItem;
				item->setData(iter.mid(iter.indexOf('|') + 1), Qt::EditRole);
				QString api("http://www.%1/index.php?m=mukio&c=index&a=init&playerID=%2");
				api = api.arg(Utils::customUrl(Utils::TuCao)).arg((code + "-%1").arg(d->model->rowCount()));
				item->setData(api, UrlRole);
				item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole);
				item->setData(File, NxtRole);
				d->model->appendRow(item);
			}
			if (sharp == -1 && d->model->rowCount() >= 2){
				emit stateChanged(task.state = Part);
			}
			else{
				int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1;
				if (i >= 0 && i < d->model->rowCount()){
					forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File);
				}
				else{
					emit stateChanged(203);
					dequeue();
				}
			}
			break;
		}
		case File:
		{
			dumpDanmaku(reply->readAll(), Utils::TuCao, false);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	auto ccRegular = [](QString &code){
		code.replace(QRegularExpression("[Hh](?=\\d)"), "cc");
		QRegularExpression r("c(c(\\d+([#_])?(\\d+)?)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return getRegular(r)(code);
	};
	d->pool.append({ ccRegular, 0, ccProcess });

	d->pool.append(Proc());
	Proc *directProc = &d->pool.last();
	directProc->process = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state){
		case None:
		{
			QUrl url = QUrl::fromUserInput(task.code);
			task.request.setUrl(url);
			task.state = File;
			forward();
			break;
		}
		case File:
		{
			Record load;
			QUrl url = reply->url();
			QByteArray data(reply->readAll());
			load.source = url.url();
			load.access = url.isLocalFile() ? url.toLocalFile() : load.source;
			load.string = QFileInfo(task.code).fileName();
			load.delay = task.delay;
			QString head = Utils::decodeTxt(data.left(512));
			if (head.startsWith("[Script Info]")){
				load.danmaku = Parse::parseComment(data, Utils::ASS);
			}
			else if (!head.startsWith("<?xml")){
				load.danmaku = Parse::parseComment(data, Utils::AcFun);
			}
			else if (head.indexOf("<packet>") != -1){
				load.danmaku = Parse::parseComment(data, Utils::Niconico);
			}
			else if (head.indexOf("<i>") != -1){
				load.danmaku = Parse::parseComment(data, Utils::Bilibili);
				QString i = QRegularExpression("(?<=<chatid>)\\d+(?=</chatid>)").match(head).captured();
				if (!i.isEmpty()){
					load.source = "http://comment.%1/%2.xml";
					load.source = load.source.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
				}
			}
			else if (head.indexOf("<c>") != -1){
				load.danmaku = Parse::parseComment(data, Utils::AcfunLocalizer);
			}
			if (load.delay != 0){
				for (Comment &c : load.danmaku){
					c.time += load.delay;
				}
			}
			Danmaku::instance()->appendToPool(&load);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	directProc->priority = -100;
	directProc->regular = [this, directProc](QString &code){
		if (code.startsWith("full?") || code.startsWith("hist?")){
			code.clear();
			return false;
		}
		QUrl u = QUrl::fromUserInput(code);
		if (!u.host().isEmpty() && !u.path().isEmpty()){
			return true;
		}
		if (QFileInfo(code).exists()){
			return true;
		}
		code.clear();
		return false;
	};

	auto fullBiProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state) {
		case None:
		{
			emit progressChanged(0);
			QString api("http://comment.%1/rolldate,%2");
			api = api.arg(Utils::customUrl(Utils::Bilibili));
			task.code = QUrlQuery(task.code.mid(5)).queryItemValue("source");
			forward(QNetworkRequest(api.arg(QFileInfo(task.code).baseName())), Page);
			break;
		}
		case Page:
		{
			QByteArray data = reply->readAll();
			QJsonArray date = QJsonDocument::fromJson(data).array();
			if (date.isEmpty()) {
				emit stateChanged(203);
				dequeue();
				break;
			}
			QJsonObject head = date.first().toObject();
			QString url("http://comment.%1/dmroll,%2,%3");
			url = url.arg(Utils::customUrl(Utils::Bilibili));
			url = url.arg(head["timestamp"].toVariant().toInt());
			url = url.arg(QFileInfo(task.code).baseName());
			QNetworkRequest request(url);
			request.setAttribute(QNetworkRequest::User, data);
			forward(request, Code);
			break;
		}
		case Code:
		{
			QByteArray data = task.request.attribute(QNetworkRequest::User).toByteArray();
			QJsonArray date = QJsonDocument::fromJson(data).array();
			QMap<int, int> count;
			for (auto iter : date) {
				QJsonObject item = iter.toObject();
				count[item["timestamp"].toVariant().toInt()] += item["new"].toVariant().toInt();
			}

			data = reply->readAll();
			if (count.size() >= 2) {
				int max = QRegularExpression("(?<=\\<max_count\\>).+(?=\\</max_count\\>)").match(data).captured().toInt();
				int now = 0;

				auto getHistory = [d, &count, &task](int date) {
					QString url("http://comment.%1/dmroll,%2,%3");
					url = url.arg(Utils::customUrl(Utils::Bilibili));
					url = url.arg(date);
					url = url.arg(QFileInfo(task.code).baseName());
					return d->manager.get(QNetworkRequest(url));
				};

				for (auto iter = count.begin() + 1;; ++iter) {
					now += iter.value();
					if (iter + 1 == count.end()) {
						d->remain += getHistory(iter.key());
						break;
					}
					else if (now + (iter + 1).value() > max) {
						d->remain += getHistory(iter.key());
						now = 0;
					}
				}

				auto pool = QSharedPointer<QVector<Parse::ResultDelegate>>::create();
				pool->append(Parse::parseComment(data, Utils::Bilibili));

				double total = d->remain.size() + 2;
				for (QNetworkReply *iter : d->remain) {
					connect(iter, &QNetworkReply::finished, [=, &task]() {
						QByteArray data = iter->readAll();
						pool->append(Parse::parseComment(data, Utils::Bilibili));
						switch (iter->error()) {
						case QNetworkReply::NoError:
							emit progressChanged((total - d->remain.size()) / total);
						case QNetworkReply::OperationCanceledError:
							if (d->remain.isEmpty() && !pool->empty()) {
								Record load;
								load.full = true;
								for (auto &iter : *pool) {
									load.danmaku.append(iter);
								}
								load.source = task.code;
								Danmaku::instance()->appendToPool(&load);
								emit stateChanged(task.state = None);
								dequeue();
							}
						default:
							break;
						}
					});
				}

				emit progressChanged(2 / total);
				emit stateChanged(task.state = File);
				break;
			}
			else {
				emit progressChanged(1);
				dumpDanmaku(data, Utils::Bilibili, true);
				emit stateChanged(task.state = None);
				dequeue();
				break;
			}
		}
		}
	};

	auto fullBiRegular = QRegularExpression("^full\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml$");
	fullBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
	d->pool.append({ getRegular(fullBiRegular), 100, fullBiProcess });

	auto histBiProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state){
		case None:
		{
			QUrlQuery query(task.code.mid(5));
			task.code = query.queryItemValue("source");
			QString cid = QFileInfo(task.code).baseName();
			QString dat = query.queryItemValue("date");
			QString url;
			QNetworkRequest request;
			if (dat != "0" && dat.toUInt() != QDateTime(QDate::currentDate()).toTime_t()){
				url = QString("http://comment.%1/dmroll,%2,%3");
				url = url.arg(Utils::customUrl(Utils::Bilibili));
				url = url.arg(dat).arg(cid);
				int limit = QDateTime(QDateTime::fromTime_t(dat.toInt()).date().addDays(1)).toTime_t();
				request.setAttribute(QNetworkRequest::User, limit);
			}
			else{
				url = QString("http://comment.%1/%2.xml").arg(Utils::customUrl(Utils::Bilibili));
				url = url.arg(cid);
			}
			request.setUrl(url);
			forward(request, File);
			break;
		}
		case File:
		{
			Record load;
			load.danmaku = Parse::parseComment(reply->readAll(), Utils::Bilibili);
			load.source = task.code;
			for (Record &iter : Danmaku::instance()->getPool()){
				if (iter.source == load.source){
					iter.full = false;
					iter.danmaku.clear();
					iter.limit = 1;
					break;
				}
			}
			load.limit = task.request.attribute(QNetworkRequest::User).toInt();
			Danmaku::instance()->appendToPool(&load);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	auto histBiRegular = QRegularExpression("^hist\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml&date=\\d+$");
	histBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
	d->pool.append({ getRegular(histBiRegular), 100, histBiProcess });

	connect(this, &Load::stateChanged, [this](int code){
		switch (code){
		case None:
		case Page:
		case Part:
		case Code:
		case File:
			break;
		default:
		{
			Q_D(Load);
			if (!d->tryNext()){
				emit errorOccured(code);
			}
			break;
		}
		}
	});
}
コード例 #12
0
ファイル: TTriadEditor.cpp プロジェクト: kaniini/hyne
QWidget *TTriadEditor::buildPage1()
{
	QWidget *ret = new QWidget(this);

	QFont font;
	font.setPointSize(10);

	cardE_model = new QStandardItemModel(ret);
	cardE_view = new QTreeView(ret);
	cardE_view->setModel(cardE_model);
	cardE_view->setEditTriggers(QAbstractItemView::DoubleClicked);
	cardE_view->setFont(font);
	cardE_view->setItemDelegate(new SpinBoxDelegate(ret));
	cardE_view->setIndentation(0);
	cardE_view->setItemsExpandable(false);
	cardE_view->header()->setStretchLastSection(false);
	cardE_view->setUniformRowHeights(true);
	cardE_view->setAllColumnsShowFocus(true);

	cardE_model2 = new QStandardItemModel(ret);
	cardE_view2 = new QTreeView(ret);
	cardE_view2->setModel(cardE_model2);
	cardE_view2->setEditTriggers(QAbstractItemView::DoubleClicked);
	cardE_view2->setFont(font);
	cardE_view2->setItemDelegate(new SpinBoxDelegate(ret));
	cardE_view2->setIndentation(0);
	cardE_view2->setItemsExpandable(false);
	cardE_view2->header()->setStretchLastSection(false);
	cardE_view2->setUniformRowHeights(true);
	cardE_view2->setAllColumnsShowFocus(true);

	QStringList labels;
	QStandardItem *standardItem;
	QIcon cardIcon(":/images/icons/carte.png");

	labels << tr("Nom") << tr("Qté");
	cardE_model->setHorizontalHeaderLabels(labels);

	for(quint8 i=0 ; i<77 ; ++i)
	{
		if(i % 11 == 0) {
			QList<QStandardItem *> items;

			standardItem = new QStandardItem(tr("Niveau %1").arg(i/11 + 1));
			standardItem->setEditable(false);
			standardItem->setEnabled(false);
			standardItem->setCheckable(false);
			standardItem->setData(-1, Qt::UserRole+2);
			items.append(standardItem);

			standardItem = new QStandardItem();
			standardItem->setEditable(false);
			standardItem->setEnabled(false);
			standardItem->setCheckable(false);
			standardItem->setData(-1, Qt::UserRole+2);
			items.append(standardItem);

			cardE_model->appendRow(items);
		}

		QList<QStandardItem *> items;

		standardItem = new QStandardItem(Data::cards().at(i));
		standardItem->setEditable(false);
		standardItem->setCheckable(true);
		standardItem->setIcon(cardIcon);
		standardItem->setData(i, Qt::UserRole+2);
		items.append(standardItem);

		standardItem = new QStandardItem();
		standardItem->setData(i, Qt::UserRole+2);
		standardItem->setData(SpinBoxDelegate::SpinBox127, Qt::UserRole);
		items.append(standardItem);

		cardE_model->appendRow(items);
	}

	cardE_view->header()->HEADER_VIEW_SET_RESIZE_MODE(0, QHeaderView::Stretch);
	cardE_view->header()->HEADER_VIEW_SET_RESIZE_MODE(1, QHeaderView::ResizeToContents);

	labels.replace(1, tr("Possesseur"));
	cardE_model2->setHorizontalHeaderLabels(labels);

	for(quint8 i=0 ; i<33 ; ++i)
	{
		if(i % 11 == 0) {
			QList<QStandardItem *> items;

			standardItem = new QStandardItem(tr("Niveau %1").arg(i/11 + 8));
			standardItem->setEditable(false);
			standardItem->setEnabled(false);
			standardItem->setCheckable(false);
			standardItem->setData(-1, Qt::UserRole+2);
			items.append(standardItem);

			standardItem = new QStandardItem();
			standardItem->setEditable(false);
			standardItem->setEnabled(false);
			standardItem->setCheckable(false);
			standardItem->setData(-1, Qt::UserRole+2);
			items.append(standardItem);

			cardE_model2->appendRow(items);
		}

		QList<QStandardItem *> items;

		standardItem = new QStandardItem(Data::cards().at(77+i));
		standardItem->setEditable(false);
		standardItem->setCheckable(true);
		standardItem->setIcon(cardIcon);
		standardItem->setData(i, Qt::UserRole+2);
		items.append(standardItem);

		standardItem = new QStandardItem();
		standardItem->setData(i, Qt::UserRole+2);
		standardItem->setData(SpinBoxDelegate::ComboBoxLocations, Qt::UserRole);
		items.append(standardItem);

		cardE_model2->appendRow(items);
	}

	cardE_view2->header()->HEADER_VIEW_SET_RESIZE_MODE(0, QHeaderView::ResizeToContents);
	cardE_view2->header()->HEADER_VIEW_SET_RESIZE_MODE(1, QHeaderView::Stretch);

	font.setPixelSize(10);
	QString selectAll = tr("Sélectionner tout");
	QCheckBox *selectAll1 = new QCheckBox(selectAll, ret);
	QCheckBox *selectAll2 = new QCheckBox(selectAll, ret);
	selectAll1->setFont(font);
	selectAll2->setFont(font);
	QWidget *qtyAll = new QWidget;
	QPushButton *qtyAllOK = new QPushButton(tr("Tout"), qtyAll);
	QPushButton *squallAll = new QPushButton(tr("Squall"), ret);
	qtyAllOK->setFont(font);
	squallAll->setFont(font);
	qtyAllSpin = new QSpinBox(qtyAll);
	qtyAllSpin->setRange(0, 127);
	QHBoxLayout *qtyLayout = new QHBoxLayout(qtyAll);
	qtyLayout->addWidget(qtyAllSpin, 1);
	qtyLayout->addWidget(qtyAllOK);
	qtyLayout->setContentsMargins(QMargins());

	cardPreview = new QLabel(ret);
	setCardPreview(110);

	connect(selectAll1, SIGNAL(toggled(bool)), SLOT(selectAll1(bool)));
	connect(selectAll2, SIGNAL(toggled(bool)), SLOT(selectAll2(bool)));
	connect(qtyAllOK, SIGNAL(released()), SLOT(qtyAll()));
	connect(squallAll, SIGNAL(released()), SLOT(squallAll()));
	connect(cardE_view->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(changeCardPreview()));
	connect(cardE_view2->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(changeCardPreview2()));

	HelpWidget *info = new HelpWidget(16, tr("<b>Case cochée :</b> carte connue<br/><b>Possesseur :</b> joueur "
											 "possédant la carte rare, mettre Squall pour l'avoir dans votre jeu."), ret);

	QGridLayout *layout = new QGridLayout(ret);
	layout->addWidget(info, 0, 2, 2, 1, Qt::AlignTop);
	layout->addWidget(cardPreview, 0, 3, 2, 1, Qt::AlignRight);
	layout->addWidget(cardE_view, 0, 0, 3, 2);
	layout->addWidget(selectAll1, 3, 0, Qt::AlignLeft);
	layout->addWidget(qtyAll, 3, 1, Qt::AlignRight);
	layout->addWidget(cardE_view2, 2, 2, 1, 2);
	layout->addWidget(selectAll2, 3, 2, Qt::AlignLeft);
	layout->addWidget(squallAll, 3, 3, Qt::AlignRight);

	return ret;
}
コード例 #13
0
ファイル: katesessionapplet.cpp プロジェクト: UIKit0/kate
void KateSessionApplet::initSessionFiles()
{
    // Obtain list of items previously configured as hidden
    const QStringList hideList = config().readEntry("hideList", QStringList());

    // Construct a full list of items (m_fullList) so we can display them
    // in the config dialog, but leave out the hidden stuff for m_kateModel
    // that is actually displayed
    int index=0;
    QStandardItem *item = new QStandardItem();
    item->setData(i18n("Start Kate (no arguments)"), Qt::DisplayRole);
    item->setData( KIcon( "kate" ), Qt::DecorationRole );
    item->setData( index++, Index );
    m_fullList << item->data(Qt::DisplayRole).toString();
    if (!hideList.contains(item->data(Qt::DisplayRole).toString())) {
        m_kateModel->appendRow(item);
    }

    item = new QStandardItem();
    item->setData( i18n("New Kate Session"), Qt::DisplayRole);
    item->setData( KIcon( "document-new" ), Qt::DecorationRole );
    item->setData( index++, Index );
    m_fullList << item->data(Qt::DisplayRole).toString();
    if (!hideList.contains(item->data(Qt::DisplayRole).toString())) {
        m_kateModel->appendRow(item);
    }

    item = new QStandardItem();
    item->setData( i18n("New Anonymous Session"), Qt::DisplayRole);
    item->setData( index++, Index );
    item->setData( KIcon( "document-new" ), Qt::DecorationRole );
    m_fullList << item->data(Qt::DisplayRole).toString();
    if (!hideList.contains(item->data(Qt::DisplayRole).toString())) {
        m_kateModel->appendRow(item);
    }

    const QStringList list = KGlobal::dirs()->findAllResources( "data", "kate/sessions/*.katesession", KStandardDirs::NoDuplicates );
    KUrl url;
    for (QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it)
    {
        url.setPath(*it);
        QString name=url.fileName();
        name = QUrl::fromPercentEncoding(QFile::encodeName(url.fileName()));
        name.chop(12);///.katesession==12
/*        KConfig _config( *it, KConfig::SimpleConfig );
        KConfigGroup config(&_config, "General" );
        QString name =  config.readEntry( "Name" );*/
        m_sessions.append( name );
    }
    qSort(m_sessions.begin(),m_sessions.end(),katesessions_compare_sessions);
    for(QStringList::ConstIterator it=m_sessions.constBegin();it!=m_sessions.constEnd();++it)
    {
        m_fullList << *it;
        if (!hideList.contains(*it)) {
            item = new QStandardItem();
            item->setData(*it, Qt::DisplayRole);
            item->setData( index++, Index );
            m_kateModel->appendRow( item);
        }
    }
}
コード例 #14
0
void VideosWindow::browseAllVideos(uint browseId, int remainingCount, uint index, QString objectId, GHashTable *metadata)
{
    if (this->browseId != browseId) return;

    if (index == 0) {
        recordingsBufferList.clear();
        filmsBufferList.clear();

        if (sortByDate->isChecked()) {
            int delta = remainingCount+1 - objectModel->rowCount();
            if (delta > 0)
                for (int i = 0; i < delta; i++)
                    objectModel->appendRow(new QStandardItem());
            else
                for (int i = delta; i < 0; i++)
                    objectModel->removeRow(objectModel->rowCount()-1);
        }
    }

    if (metadata != NULL) {
        GValue *v;

        v = mafw_metadata_first(metadata, MAFW_METADATA_KEY_TITLE);
        QString title = v ? QString::fromUtf8(g_value_get_string (v)) : tr("(unknown clip)");

        v = mafw_metadata_first(metadata, MAFW_METADATA_KEY_VIDEO_SOURCE);
        QString source = v ? QString::fromUtf8(g_value_get_string (v)) : QString();

        v = mafw_metadata_first(metadata, MAFW_METADATA_KEY_DURATION);
        int duration = v ? g_value_get_int (v) : Duration::Unknown;

        QStandardItem *item = sortByCategory->isChecked() ? new QStandardItem() : objectModel->item(index);

        v = mafw_metadata_first(metadata, MAFW_METADATA_KEY_PAUSED_THUMBNAIL_URI);
        if (v != NULL) {
            const gchar* filename = g_value_get_string(v); // the uri is really a filename
            if (filename != NULL)
                item->setIcon(QIcon(QString::fromUtf8(filename)));
        } else {
            v = mafw_metadata_first(metadata, MAFW_METADATA_KEY_THUMBNAIL_URI);
            if (v != NULL) {
                const gchar* file_uri = g_value_get_string(v); // here uri is a uri
                gchar* filename;
                if (file_uri != NULL && (filename = g_filename_from_uri(file_uri, NULL, NULL)) != NULL)
                    item->setIcon(QIcon(QString::fromUtf8(filename)));
            } else {
                item->setIcon(QIcon::fromTheme(defaultVideoIcon));
            }
        }

        item->setData(objectId, UserRoleObjectID);
        item->setData(title, UserRoleTitle);

        if (sortByCategory->isChecked()) {
            item->setData(duration, UserRoleSongDuration);
            (source.startsWith("noki://") ? recordingsBufferList : filmsBufferList).append(item);
        }
        else { // sortByDate->isChecked()
            if (duration != Duration::Unknown) {
                QTime t(0, 0);
                t = t.addSecs(duration);
                item->setData(t.toString("h:mm:ss"), UserRoleValueText);
            } else
                item->setData("-:--:--", UserRoleValueText);
        }
    }

    if (remainingCount == 0) {
        disconnect(mafwTrackerSource, SIGNAL(browseResult(uint,int,uint,QString,GHashTable*,QString)),
                   this, SLOT(browseAllVideos(uint,int,uint,QString,GHashTable*)));

        if (sortByCategory->isChecked()) {
            bool drawHeaders = !recordingsBufferList.isEmpty() && !filmsBufferList.isEmpty();
            int delta = recordingsBufferList.size() + filmsBufferList.size() - objectModel->rowCount();
            if (drawHeaders) delta += 2;

            if (delta > 0)
                for (int i = 0; i < delta; i++)
                    objectModel->appendRow(new QStandardItem());
            else
                for (int i = delta; i < 0; i++)
                    objectModel->removeRow(objectModel->rowCount()-1);

            int i = 0;

            if (!recordingsBufferList.isEmpty()) {
                if (drawHeaders) {
                    objectModel->item(i)->setData(true, UserRoleHeader);
                    objectModel->item(i)->setData(tr("Recorded by device camera"), UserRoleTitle);
                    objectModel->item(i)->setData(Duration::Blank, UserRoleSongDuration);
                    ++i;
                }

                while (!recordingsBufferList.isEmpty()) {
                    objectModel->item(i)->setData(false, UserRoleHeader);
                    objectModel->item(i)->setData(recordingsBufferList.first()->data(UserRoleTitle), UserRoleTitle);
                    objectModel->item(i)->setData(recordingsBufferList.first()->data(UserRoleObjectID), UserRoleObjectID);
                    objectModel->item(i)->setData(recordingsBufferList.first()->data(UserRoleSongDuration), UserRoleSongDuration);
                    objectModel->item(i)->setIcon(recordingsBufferList.first()->icon());
                    delete recordingsBufferList.takeFirst();
                    ++i;
                }
            }

            if (!filmsBufferList.isEmpty()) {
                if (drawHeaders) {
                    objectModel->item(i)->setData(true, UserRoleHeader);
                    objectModel->item(i)->setData(tr("Films"), UserRoleTitle);
                    objectModel->item(i)->setData(Duration::Blank, UserRoleSongDuration);
                    ++i;
                }

                while (!filmsBufferList.isEmpty()) {
                    objectModel->item(i)->setData(false, UserRoleHeader);
                    objectModel->item(i)->setData(filmsBufferList.first()->data(UserRoleTitle), UserRoleTitle);
                    objectModel->item(i)->setData(filmsBufferList.first()->data(UserRoleObjectID), UserRoleObjectID);
                    objectModel->item(i)->setData(filmsBufferList.first()->data(UserRoleSongDuration), UserRoleSongDuration);
                    objectModel->item(i)->setIcon(filmsBufferList.first()->icon());
                    delete filmsBufferList.takeFirst();
                    ++i;
                }
            }
        }

        this->setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
    }
コード例 #15
0
ファイル: qgspgtablemodel.cpp プロジェクト: exlimit/QGIS
void QgsPgTableModel::addTableEntry( const QgsPostgresLayerProperty &layerProperty )
{
  QgsDebugMsg( layerProperty.toString() );

  // is there already a root item with the given scheme Name?
  QStandardItem *schemaItem = nullptr;

  for ( int i = 0; i < layerProperty.size(); i++ )
  {
    QgsWkbTypes::Type wkbType = layerProperty.types[ i ];
    int srid = layerProperty.srids[ i ];

    if ( wkbType == QgsWkbTypes::Unknown && layerProperty.geometryColName.isEmpty() )
    {
      wkbType = QgsWkbTypes::NoGeometry;
    }

    QString tip;
    if ( wkbType == QgsWkbTypes::Unknown )
    {
      tip = tr( "Specify a geometry type in the '%1' column" ).arg( tr( "Data Type" ) );
    }
    else if ( wkbType != QgsWkbTypes::NoGeometry && srid == INT_MIN )
    {
      tip = tr( "Enter a SRID into the '%1' column" ).arg( tr( "SRID" ) );
    }
    else if ( !layerProperty.pkCols.isEmpty() )
    {
      tip = tr( "Select columns in the '%1' column that uniquely identify features of this layer" ).arg( tr( "Feature id" ) );
    }

    QStandardItem *schemaNameItem = new QStandardItem( layerProperty.schemaName );
    QStandardItem *typeItem = new QStandardItem( iconForWkbType( wkbType ), wkbType == QgsWkbTypes::Unknown ? tr( "Select..." ) : QgsPostgresConn::displayStringForWkbType( wkbType ) );
    typeItem->setData( wkbType == QgsWkbTypes::Unknown, Qt::UserRole + 1 );
    typeItem->setData( wkbType, Qt::UserRole + 2 );
    if ( wkbType == QgsWkbTypes::Unknown )
      typeItem->setFlags( typeItem->flags() | Qt::ItemIsEditable );

    QStandardItem *geomTypeItem = new QStandardItem( QgsPostgresConn::displayStringForGeomType( layerProperty.geometryColType ) );

    QStandardItem *tableItem = new QStandardItem( layerProperty.tableName );
    QStandardItem *commentItem = new QStandardItem( layerProperty.tableComment );
    QStandardItem *geomItem  = new QStandardItem( layerProperty.geometryColName );
    QStandardItem *sridItem  = new QStandardItem( wkbType != QgsWkbTypes::NoGeometry ? QString::number( srid ) : QLatin1String( "" ) );
    sridItem->setEditable( wkbType != QgsWkbTypes::NoGeometry && srid == INT_MIN );
    if ( sridItem->isEditable() )
    {
      sridItem->setText( tr( "Enter..." ) );
      sridItem->setFlags( sridItem->flags() | Qt::ItemIsEditable );
    }

    QStandardItem *pkItem = new QStandardItem( QLatin1String( "" ) );
    if ( !layerProperty.pkCols.isEmpty() )
    {
      pkItem->setText( tr( "Select..." ) );
      pkItem->setFlags( pkItem->flags() | Qt::ItemIsEditable );
    }
    else
      pkItem->setFlags( pkItem->flags() & ~Qt::ItemIsEditable );

    pkItem->setData( layerProperty.pkCols, Qt::UserRole + 1 );
    pkItem->setData( "", Qt::UserRole + 2 );

    QStandardItem *selItem = new QStandardItem( QLatin1String( "" ) );
    selItem->setFlags( selItem->flags() | Qt::ItemIsUserCheckable );
    selItem->setCheckState( Qt::Checked );
    selItem->setToolTip( tr( "Disable 'Fast Access to Features at ID' capability to force keeping the attribute table in memory (e.g. in case of expensive views)." ) );

    QStandardItem *sqlItem = new QStandardItem( layerProperty.sql );

    QList<QStandardItem *> childItemList;

    childItemList << schemaNameItem;
    childItemList << tableItem;
    childItemList << commentItem;
    childItemList << geomItem;
    childItemList << geomTypeItem;
    childItemList << typeItem;
    childItemList << sridItem;
    childItemList << pkItem;
    childItemList << selItem;
    childItemList << sqlItem;

    Q_FOREACH ( QStandardItem *item, childItemList )
    {
      if ( tip.isEmpty() )
      {
        item->setFlags( item->flags() | Qt::ItemIsSelectable );
        item->setToolTip( QLatin1String( "" ) );
      }
      else
      {
        item->setFlags( item->flags() & ~Qt::ItemIsSelectable );

        if ( item == schemaNameItem )
          item->setData( QgsApplication::getThemeIcon( QStringLiteral( "/mIconWarning.svg" ) ), Qt::DecorationRole );

        if ( item == schemaNameItem || item == tableItem || item == geomItem )
        {
          item->setToolTip( tip );
        }
      }
    }

    if ( !schemaItem )
    {
      QList<QStandardItem *> schemaItems = findItems( layerProperty.schemaName, Qt::MatchExactly, DbtmSchema );

      // there is already an item for this schema
      if ( !schemaItems.isEmpty() )
      {
        schemaItem = schemaItems.at( DbtmSchema );
      }
      else
      {
        // create a new toplevel item for this schema
        schemaItem = new QStandardItem( layerProperty.schemaName );
        schemaItem->setFlags( Qt::ItemIsEnabled );
        invisibleRootItem()->setChild( invisibleRootItem()->rowCount(), schemaItem );
      }
    }

    schemaItem->appendRow( childItemList );

    ++mTableCount;
  }
}
コード例 #16
0
void PowerManagementRecordGui::onMessageReceived(const QString &response)
{
    QStringList breakdown = response.split(",");
    QString command = breakdown[0].right(1);
// Error Code
    switch (command[0].toAscii())
    {
// Show Free Space
        case 'F':
        {
            int freeSpace = breakdown[2].toInt()*breakdown[1].toInt()/2048;
            PowerManagementRecordUi.diskSpaceAvailable->setText(QString("%1 M")\
                                                    .arg(freeSpace, 0, 10));
            break;
        }
/* Directory listing.
Fill a predefined model with strings from the response breakdown.
The response will be a comma separated list of items preceded by a type.
*/
        case 'D':
        {
            model->clear();
            if (breakdown.size() <= 1) break;
            for (int i=1; i<breakdown.size(); i++)
            {
                QChar type = breakdown[i][0];
                bool ok;
                QString fileSize = QString("%1")
                    .arg((float)breakdown[i].mid(1,8).toInt(&ok,16)/1000000,8,'f',3);
                if (type == 'd')
                    fileSize = "";
                if ((type == 'f') || (type == 'd'))
                {
                    QString fileName = breakdown[i].mid(9,breakdown[i].length()-1);
                    QFont font;
                    if (type == 'd') font.setBold(true);
                    QStandardItem *nameItem = new QStandardItem(fileName);
                    QStandardItem *sizeItem = new QStandardItem(fileSize);
                    QList<QStandardItem *> row;
                    nameItem->setFont(font);
                    nameItem->setData(Qt::AlignLeft, Qt::TextAlignmentRole);
                    sizeItem->setData(Qt::AlignRight, Qt::TextAlignmentRole);
                    row.append(nameItem);
                    row.append(sizeItem);
                    nameItem->setData(QVariant(type));
//                    item->setIcon(...);
                    model->appendRow(row);
                }
            }
            break;
        }
/* Directory listing incremental.
Fill a predefined model with a string from the response breakdown. A series of
responses will give each entry in the listing, terminated by an empty filename.
This will ease the communications load by requesting each entry only after
the previous entry has been fully received.
*/
        case 'd':
        {
            if (breakdown.size() < 1) break;
// Empty parameters received indicates the directory listing has ended.
            directoryEnded = (breakdown.size() == 1);
            if (directoryEnded) break;
            nextDirectoryEntry = true;
            for (int i=1; i<breakdown.size(); i++)
            {
                QChar type = breakdown[i][0];
                bool ok;
                QString fileSize = QString("%1")
                    .arg((float)breakdown[i].mid(1,8).toInt(&ok,16)/1000000,8,'f',3);
                if (type == 'd')
                    fileSize = "";
                if ((type == 'f') || (type == 'd'))
                {
                    QString fileName = breakdown[i].mid(9,breakdown[i].length()-1);
                    QFont font;
                    if (type == 'd') font.setBold(true);
                    QStandardItem *nameItem = new QStandardItem(fileName);
                    QStandardItem *sizeItem = new QStandardItem(fileSize);
                    QList<QStandardItem *> row;
                    nameItem->setFont(font);
                    nameItem->setData(Qt::AlignLeft, Qt::TextAlignmentRole);
                    sizeItem->setData(Qt::AlignRight, Qt::TextAlignmentRole);
                    row.append(nameItem);
                    row.append(sizeItem);
                    nameItem->setData(QVariant(type));
//                    item->setIcon(...);
                    model->appendRow(row);
                }
/* Request the next entry by sending another incremental directory command with
no directory name. */
                socket->write("fd\r\n");
            }
            break;
        }
// Status of recording and open files.
// The write and read file handles are retrieved from this
        case 's':
        {
            if (breakdown.size() <= 1) break;
            recordingOn = (breakdown[1].toInt() & 0x02) > 0;
            if (recordingOn)  // recording on
                PowerManagementRecordUi.startButton->
                    setStyleSheet("background-color:lightgreen;");
            else
                PowerManagementRecordUi.startButton->
                    setStyleSheet("background-color:lightpink;");
            if (breakdown.size() <= 2) break;
            writeFileHandle = breakdown[2].toInt();
            writeFileOpen = (writeFileHandle < 255);
            if (writeFileOpen)
            {
                PowerManagementRecordUi.recordFileButton->
                    setStyleSheet("background-color:lightgreen;");
                PowerManagementRecordUi.recordFileName->setText(breakdown[3]);
            }
            else
                PowerManagementRecordUi.recordFileButton->
                    setStyleSheet("background-color:lightpink;");
            if (breakdown.size() <= 3) break;
            readFileHandle = breakdown[3].toInt();
            readFileOpen = (readFileHandle < 255);
            if (readFileOpen)
                 PowerManagementRecordUi.readFileName->setText(breakdown[3]);
           break;
        }
// Open a file for recording.
        case 'W':
        {
            writeFileHandle = extractValue(response);
            break;
        }
        case 'E':
        {
            QString errorText[19] = {"Hard Disk Error",
                                     "Internal Error",
                                     "Medium Not Ready",
                                     "File not Found",
                                     "Path not Found",
                                     "Invalid Path Format",
                                     "Access denied or directory full",
                                     "File Exists",
                                     "File/directory object invalid",
                                     "Drive write protected",
                                     "Logical drive number invalid",
                                     "Volume has no work area",
                                     "No valid FAT volume",
                                     "Format aborted: parameter error",
                                     "Timeout waiting for access",
                                     "File sharing policy violation",
                                     "LFN working buffer could not be allocated",
                                     "Too many open files",
                                     "Invalid Parameter"};
            int status = breakdown[1].toInt();
            if ((status > 0) && (status < 20))
                PowerManagementRecordUi.errorLabel->setText(errorText[status-1]);
            break;
        }
    }
}
コード例 #17
0
void CommonEventsDatas::read(const QJsonObject &json){
    QStandardItem* item;
    QJsonArray jsonList;
    SystemEvent* ev;
    SuperListItem* super;
    SystemCommonReaction* react;
    SystemCommonObject* object;

    // Clear
    SuperListItem::deleteModel(m_modelEventsSystem, false);
    SuperListItem::deleteModel(m_modelEventsUser, false);
    SuperListItem::deleteModel(m_modelStates, false);
    SuperListItem::deleteModel(m_modelCommonReactors, false);
    SuperListItem::deleteModel(m_modelCommonObjects, false);

    // Events
    jsonList = json["eventsSystem"].toArray();
    for (int i = 0; i < jsonList.size(); i++){
        item = new QStandardItem;
        ev = new SystemEvent;
        ev->read(jsonList[i].toObject());
        item->setData(QVariant::fromValue(reinterpret_cast<quintptr>(ev)));
        item->setText(ev->toString());
        m_modelEventsSystem->appendRow(item);
    }
    jsonList = json["eventsUser"].toArray();
    for (int i = 0; i < jsonList.size(); i++){
        item = new QStandardItem;
        ev = new SystemEvent;
        ev->read(jsonList[i].toObject());
        item->setData(QVariant::fromValue(reinterpret_cast<quintptr>(ev)));
        item->setText(ev->toString());
        m_modelEventsUser->appendRow(item);
    }

    // States
    jsonList = json["states"].toArray();
    for (int i = 0; i < jsonList.size(); i++){
        item = new QStandardItem;
        super = new SuperListItem;
        super->read(jsonList[i].toObject());
        item->setData(QVariant::fromValue(reinterpret_cast<quintptr>(super)));
        item->setText(super->toString());
        m_modelStates->appendRow(item);
    }

    // Common reactors
    jsonList = json["commonReactors"].toArray();
    for (int i = 0; i < jsonList.size(); i++){
        item = new QStandardItem;
        react = new SystemCommonReaction;
        react->read(jsonList[i].toObject());
        item->setData(QVariant::fromValue(reinterpret_cast<quintptr>(react)));
        item->setText(react->toString());
        m_modelCommonReactors->appendRow(item);
    }

    // Common objects
    jsonList = json["commonObjects"].toArray();
    for (int i = 0; i < jsonList.size(); i++){
        item = new QStandardItem;
        object = new SystemCommonObject;
        object->read(jsonList[i].toObject());
        item->setData(QVariant::fromValue(reinterpret_cast<quintptr>(object)));
        item->setText(object->toString());
        m_modelCommonObjects->appendRow(item);
    }
}
コード例 #18
0
ファイル: kcm.cpp プロジェクト: cmacq2/plasma-desktop
void KCMLookandFeel::load()
{
    m_package = Plasma::PluginLoader::self()->loadPackage(QStringLiteral("Plasma/LookAndFeel"));
    KConfigGroup cg(KSharedConfig::openConfig(QStringLiteral("kdeglobals")), "KDE");
    const QString packageName = cg.readEntry("LookAndFeelPackage", QString());
    if (!packageName.isEmpty()) {
        m_package.setPath(packageName);
    }

    if (!m_package.metadata().isValid()) {
        return;
    }

    setSelectedPlugin(m_package.metadata().pluginName());

    m_model->clear();

    const QList<Plasma::Package> pkgs = availablePackages();
    for (const Plasma::Package &pkg : pkgs) {
        if (!pkg.metadata().isValid()) {
            continue;
        }
        QStandardItem* row = new QStandardItem(pkg.metadata().name());
        row->setData(pkg.metadata().pluginName(), PluginNameRole);
        row->setData(pkg.filePath("previews", QStringLiteral("preview.png")), ScreenhotRole);

        //What the package provides
        row->setData(!pkg.filePath("splashmainscript").isEmpty(), HasSplashRole);
        row->setData(!pkg.filePath("lockscreenmainscript").isEmpty(), HasLockScreenRole);
        row->setData(!pkg.filePath("runcommandmainscript").isEmpty(), HasRunCommandRole);
        row->setData(!pkg.filePath("logoutmainscript").isEmpty(), HasLogoutRole);

        if (!pkg.filePath("defaults").isEmpty()) {
            KSharedConfigPtr conf = KSharedConfig::openConfig(pkg.filePath("defaults"));
            KConfigGroup cg(conf, "kdeglobals");
            cg = KConfigGroup(&cg, "General");
            bool hasColors = !cg.readEntry("ColorScheme", QString()).isEmpty();
            row->setData(hasColors, HasColorsRole);
            if (!hasColors) {
                hasColors = !pkg.filePath("colors").isEmpty();
            }
            cg = KConfigGroup(&cg, "KDE");
            row->setData(!cg.readEntry("widgetStyle", QString()).isEmpty(), HasWidgetStyleRole);
            cg = KConfigGroup(conf, "kdeglobals");
            cg = KConfigGroup(&cg, "Icons");
            row->setData(!cg.readEntry("Theme", QString()).isEmpty(), HasIconsRole);

            cg = KConfigGroup(conf, "kdeglobals");
            cg = KConfigGroup(&cg, "Theme");
            row->setData(!cg.readEntry("name", QString()).isEmpty(), HasPlasmaThemeRole);

            cg = KConfigGroup(conf, "kcminputrc");
            cg = KConfigGroup(&cg, "Mouse");
            row->setData(!cg.readEntry("cursorTheme", QString()).isEmpty(), HasCursorsRole);

            cg = KConfigGroup(conf, "kwinrc");
            cg = KConfigGroup(&cg, "WindowSwitcher");
            row->setData(!cg.readEntry("LayoutName", QString()).isEmpty(), HasWindowSwitcherRole);

            cg = KConfigGroup(conf, "kwinrc");
            cg = KConfigGroup(&cg, "DesktopSwitcher");
            row->setData(!cg.readEntry("LayoutName", QString()).isEmpty(), HasDesktopSwitcherRole);
        }

        m_model->appendRow(row);
    }
}
コード例 #19
0
bool QgsAmsSourceSelect::connectToService( const QgsOwsConnection &connection )
{
  QString errorTitle, errorMessage;

  const QString authcfg = connection.uri().param( QStringLiteral( "authcfg" ) );
  const QString baseUrl = connection.uri().param( QStringLiteral( "url" ) );
  const QString referer = connection.uri().param( QStringLiteral( "referer" ) );
  QgsStringMap headers;
  if ( ! referer.isEmpty() )
    headers[ QStringLiteral( "Referer" )] = referer;

  bool hasPopulatedImageFormats = false;
  std::function< bool( const QString &, QStandardItem * )> visitItemsRecursive;
  visitItemsRecursive = [this, &hasPopulatedImageFormats, &visitItemsRecursive, baseUrl, authcfg, headers, &errorTitle, &errorMessage]( const QString & baseItemUrl, QStandardItem * parentItem ) -> bool
  {
    const QVariantMap serviceInfoMap = QgsArcGisRestUtils::getServiceInfo( baseItemUrl, authcfg, errorTitle, errorMessage, headers );

    if ( serviceInfoMap.isEmpty() )
    {
      return false;
    }

    if ( !hasPopulatedImageFormats )
    {
      const QString supportedFormats = serviceInfoMap[QStringLiteral( "supportedImageFormatTypes" )].toString();
      if ( !supportedFormats.isEmpty() )
      {
        populateImageEncodings( supportedFormats.split( ',' ) );
        hasPopulatedImageFormats = true;
      }
    }

    bool res = true;

    QgsArcGisRestUtils::visitFolderItems( [ =, &res ]( const QString & name, const QString & url )
    {
      QStandardItem *nameItem = new QStandardItem( name );
      nameItem->setToolTip( url );
      if ( parentItem )
        parentItem->appendRow( QList<QStandardItem *>() << nameItem );
      else
        mModel->appendRow( QList<QStandardItem *>() << nameItem );

      if ( !visitItemsRecursive( url, nameItem ) )
        res = false;
    }, serviceInfoMap, baseUrl );

    QgsArcGisRestUtils::visitServiceItems(
      [ =, &res]( const QString & name, const QString & url )
    {
      QStandardItem *nameItem = new QStandardItem( name );
      nameItem->setToolTip( url );
      if ( parentItem )
        parentItem->appendRow( QList<QStandardItem *>() << nameItem );
      else
        mModel->appendRow( QList<QStandardItem *>() << nameItem );

      if ( !visitItemsRecursive( url, nameItem ) )
        res = false;
    }, serviceInfoMap, baseUrl );

    QMap< QString, QList<QStandardItem *> > layerItems;
    QMap< QString, QString > parents;

    QgsArcGisRestUtils::addLayerItems( [ =, &layerItems, &parents]( const QString & parentLayerId, const QString & layerId, const QString & name, const QString & description, const QString & url, bool, const QString & authid, const QString & )
    {
      if ( !parentLayerId.isEmpty() )
        parents.insert( layerId, parentLayerId );

      // insert the typenames, titles and abstracts into the tree view
      QStandardItem *idItem = new QStandardItem( layerId );
      bool ok = false;
      int idInt = layerId.toInt( &ok );
      if ( ok )
      {
        // force display role to be int value, so that sorting works correctly
        idItem->setData( idInt, Qt::DisplayRole );
      }
      idItem->setData( url, UrlRole );
      idItem->setData( layerId, IdRole );
      idItem->setData( true, IsLayerRole );
      QStandardItem *nameItem = new QStandardItem( name );
      QStandardItem *abstractItem = new QStandardItem( description );
      abstractItem->setToolTip( description );
      QStandardItem *filterItem = new QStandardItem();

      mAvailableCRS[name] = QList<QString>()  << authid;

      layerItems.insert( layerId, QList<QStandardItem *>() << idItem << nameItem << abstractItem << filterItem );
    }, serviceInfoMap, baseItemUrl );

    // create layer groups
    for ( auto it = layerItems.constBegin(); it != layerItems.constEnd(); ++it )
    {
      const QString id = it.key();
      QList<QStandardItem *> row = it.value();
      const QString parentId = parents.value( id );
      QList<QStandardItem *> parentRow;
      if ( !parentId.isEmpty() )
        parentRow = layerItems.value( parentId );
      if ( !parentRow.isEmpty() )
      {
        parentRow.at( 0 )->appendRow( row );
      }
      else
      {
        if ( parentItem )
          parentItem->appendRow( row );
        else
          mModel->appendRow( row );
      }
    }

    return res;
  };

  if ( !visitItemsRecursive( baseUrl, nullptr ) )
    QMessageBox::warning( this, tr( "Error" ), tr( "Failed to retrieve service capabilities:\n%1: %2" ).arg( errorTitle, errorMessage ) );

  return true;
}
コード例 #20
0
QgsDataDefinedSizeLegendWidget::QgsDataDefinedSizeLegendWidget( const QgsDataDefinedSizeLegend *ddsLegend, const QgsProperty &ddSize, QgsMarkerSymbol *overrideSymbol, QgsMapCanvas *canvas, QWidget *parent )
  : QgsPanelWidget( parent )
  , mSizeProperty( ddSize )
  , mMapCanvas( canvas )
{
  setupUi( this );
  setPanelTitle( tr( "Data-defined size legend" ) );

  QgsMarkerSymbol *symbol = nullptr;

  if ( !ddsLegend )
  {
    radDisabled->setChecked( true );
  }
  else
  {
    if ( ddsLegend->legendType() == QgsDataDefinedSizeLegend::LegendSeparated )
      radSeparated->setChecked( true );
    else
      radCollapsed->setChecked( true );

    if ( ddsLegend->verticalAlignment() == QgsDataDefinedSizeLegend::AlignBottom )
      cboAlignSymbols->setCurrentIndex( 0 );
    else
      cboAlignSymbols->setCurrentIndex( 1 );

    symbol = ddsLegend->symbol() ? ddsLegend->symbol()->clone() : nullptr;  // may be null (undefined)
  }

  if ( overrideSymbol )
  {
    symbol = overrideSymbol;   // takes ownership
    mOverrideSymbol = true;
  }

  if ( !symbol )
  {
    symbol = QgsMarkerSymbol::createSimple( QgsStringMap() );
  }
  mSourceSymbol.reset( symbol );

  btnChangeSymbol->setEnabled( !mOverrideSymbol );

  QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( mSourceSymbol.get(), btnChangeSymbol->iconSize() );
  btnChangeSymbol->setIcon( icon );

  editTitle->setText( ddsLegend ? ddsLegend->title() : QString() );

  mSizeClassesModel = new QStandardItemModel( viewSizeClasses );
  mSizeClassesModel->setHorizontalHeaderLabels( QStringList() << tr( "Value" ) << tr( "Label" ) );
  mSizeClassesModel->setSortRole( Qt::UserRole + 1 );
  if ( ddsLegend )
  {
    groupManualSizeClasses->setChecked( !ddsLegend->classes().isEmpty() );
    Q_FOREACH ( const QgsDataDefinedSizeLegend::SizeClass &sc, ddsLegend->classes() )
    {
      QStandardItem *item = new QStandardItem( QString::number( sc.size ) );
      item->setData( sc.size );
      QStandardItem *itemLabel = new QStandardItem( sc.label );
      mSizeClassesModel->appendRow( QList<QStandardItem *>() << item << itemLabel );
    }
    mSizeClassesModel->sort( 0 );
  }

  connect( btnAddClass, &QToolButton::clicked, this, &QgsDataDefinedSizeLegendWidget::addSizeClass );
  connect( btnRemoveClass, &QToolButton::clicked, this, &QgsDataDefinedSizeLegendWidget::removeSizeClass );

  viewSizeClasses->setItemDelegateForColumn( 0, new SizeClassDelegate( viewSizeClasses ) );
  viewSizeClasses->setModel( mSizeClassesModel );
  connect( mSizeClassesModel, &QStandardItemModel::dataChanged, this, &QgsDataDefinedSizeLegendWidget::onSizeClassesChanged );

  // prepare layer and model to preview legend
  mPreviewLayer = new QgsVectorLayer( "Point?crs=EPSG:4326", "Preview", "memory" );
  mPreviewTree = new QgsLayerTree;
  mPreviewLayerNode = mPreviewTree->addLayer( mPreviewLayer );  // node owned by the tree
  mPreviewModel = new QgsLayerTreeModel( mPreviewTree );
  if ( canvas )
    mPreviewModel->setLegendMapViewData( canvas->mapUnitsPerPixel(), canvas->mapSettings().outputDpi(), canvas->scale() );
  viewLayerTree->setModel( mPreviewModel );

  connect( cboAlignSymbols, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), [ = ] { emit widgetChanged(); } );
  connect( radDisabled, &QRadioButton::clicked, this, &QgsPanelWidget::widgetChanged );
  connect( radSeparated, &QRadioButton::clicked, this, &QgsPanelWidget::widgetChanged );
  connect( radCollapsed, &QRadioButton::clicked, this, &QgsPanelWidget::widgetChanged );
  connect( groupManualSizeClasses, &QGroupBox::clicked, this, &QgsPanelWidget::widgetChanged );
  connect( btnChangeSymbol, &QPushButton::clicked, this, &QgsDataDefinedSizeLegendWidget::changeSymbol );
  connect( editTitle, &QLineEdit::textChanged, this, &QgsPanelWidget::widgetChanged );
  connect( this, &QgsPanelWidget::widgetChanged, this, &QgsDataDefinedSizeLegendWidget::updatePreview );
  updatePreview();
}
コード例 #21
0
QStandardItem* PodcastDiscoveryModel::CreateLoadingIndicator() {
  QStandardItem* item = new QStandardItem;
  item->setText(tr("Loading..."));
  item->setData(Type_LoadingIndicator, Role_Type);
  return item;
}
コード例 #22
0
void MyViewModel::initialize()
{
    auto root = this->invisibleRootItem();

    QStandardItem* entry = new QStandardItem();
    entry->setData("One", MyViewModel_Roles_Display );
    entry->setData(0, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("One", MyViewModel_Roles_Display );
    entry->setData(2, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("One", MyViewModel_Roles_Display );
    entry->setData(3, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("One", MyViewModel_Roles_Display );
    entry->setData(4, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("Two", MyViewModel_Roles_Details );
    entry->setData(5, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("Three", MyViewModel_Roles_Details );
    entry->setData(6, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("Four", MyViewModel_Roles_Details );
    entry->setData(7, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("Five", MyViewModel_Roles_Details );
    entry->setData(8, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("Six", MyViewModel_Roles_Details );
    entry->setData(9, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("Seven", MyViewModel_Roles_KeyId );
    entry->setData(10, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("Eight", MyViewModel_Roles_KeyId );
    entry->setData(11, MyViewModel_Roles_Value );
    root->appendRow(entry);

    entry = new QStandardItem();
    entry->setData("hello", MyViewModel_Roles_KeyId );
    entry->setData(12, MyViewModel_Roles_Value );
    root->appendRow(entry);

    emit rowCountChanged();
}
コード例 #23
0
void SetupPluginsDialog::updatePlugins()
{
	FModel.clear();

	int errorsCount = 0;
	int disableCount = 0;
	QDomElement pluginElem = FPluginsSetup.documentElement().firstChildElement();
	while (!pluginElem.isNull())
	{
		QUuid uuid = pluginElem.attribute("uuid");
		QString file = pluginElem.tagName();
		QString name = pluginElem.firstChildElement("name").text();
		QString version = pluginElem.firstChildElement("version").text();
		QString error = pluginElem.firstChildElement("error").text();
		QString descr = pluginElem.firstChildElement("desc").text();
		bool isEnabled = pluginElem.attribute("enabled","true") == "true";

		const IPluginInfo *info = FPluginManager->pluginInfo(uuid);
		bool isLoaded = info!=NULL;
		QString homePage = info!=NULL ? info->homePage.toString() : QString::null;

		QStringList dependsOn, dependsFor;
		if (info != NULL)
		{
			foreach(const QUuid &dependUid, FPluginManager->pluginDependencesOn(uuid))
				dependsOn.append(dependUid.toString());
			foreach(const QUuid &dependUid, FPluginManager->pluginDependencesFor(uuid))
				dependsFor.append(dependUid.toString());
		}

		QStandardItem *pluginItem = new QStandardItem(name);
		pluginItem->setData(uuid.toString(), PDR_UUID);
		pluginItem->setData(file, PDR_FILE);
		pluginItem->setData(name.isEmpty() ? file : name, PDR_NAME);
		pluginItem->setData(error.isEmpty() ? descr : error, PDR_DESCR);
		pluginItem->setData(version, PDR_VERSION);
		pluginItem->setData(homePage, PDR_HOMEPAGE);
		pluginItem->setData(isLoaded, PDR_ISLOADED);
		pluginItem->setData(isEnabled, PDR_ISENABLED);
		pluginItem->setData(dependsOn, PDR_DEPENDS_ON);
		pluginItem->setData(dependsFor, PDR_DEPENDS_FOR);
		pluginItem->setData(file+" "+name+" "+descr+" "+error, PDR_FILTER);
		pluginItem->setData(pluginItem->data(PDR_DESCR), Qt::ToolTipRole);
		
		AdvancedDelegateItem nameLabel(AdvancedDelegateItem::DisplayId);
		nameLabel.d->kind = AdvancedDelegateItem::Display;
		nameLabel.d->data = pluginItem->data(PDR_NAME);
		nameLabel.d->hints.insert(AdvancedDelegateItem::FontWeight,QFont::Bold);

		AdvancedDelegateItem versionLabel(AdvancedDelegateItem::DisplayId+1);
		versionLabel.d->kind = AdvancedDelegateItem::CustomData;
		versionLabel.d->data = pluginItem->data(PDR_VERSION);

		AdvancedDelegateItem descrLabel(AdvancedDelegateItem::makeId(AdvancedDelegateItem::Bottom,129,10));
		descrLabel.d->kind = AdvancedDelegateItem::CustomData;
		descrLabel.d->data = pluginItem->data(PDR_DESCR);

		AdvancedDelegateItems labels;
		labels.insert(nameLabel.d->id, nameLabel);
		labels.insert(versionLabel.d->id, versionLabel);
		labels.insert(descrLabel.d->id, descrLabel);
		pluginItem->setData(QVariant::fromValue<AdvancedDelegateItems>(labels), PDR_LABELS);

		if (!isEnabled)
		{
			disableCount++;
			nameLabel.d->hints.insert(AdvancedDelegateItem::Foreground, ui.tbvPlugins->palette().color(QPalette::Disabled, QPalette::Text));
		}
		else if (!isLoaded)
		{
			errorsCount++;
//			descrLabel.d->hints.insert(AdvancedDelegateItem::Foreground, Qt::red);
			descrLabel.d->hints.insert(AdvancedDelegateItem::Foreground, QColor(Qt::red));
			nameLabel.d->hints.insert(AdvancedDelegateItem::Foreground, ui.tbvPlugins->palette().color(QPalette::Disabled, QPalette::Text));
		}

		pluginItem->setCheckable(true);
		pluginItem->setCheckState(isEnabled ? Qt::Checked : Qt::Unchecked);

		FModel.appendRow(pluginItem);
		FPluginItem.insert(uuid, pluginItem);
		FItemElement.insert(pluginItem, pluginElem);

		pluginElem = pluginElem.nextSiblingElement();
	}
コード例 #24
0
ファイル: stitcherworkspace.cpp プロジェクト: ng110/hawk
void StitcherWorkspace::loadGeometry() {
    /*
       This is a prefix to distinguish Hawk Geometry properties from the
       normal widget properties
    */
    const QString tag("HawkGeometry_");
    QList<QGraphicsItem *> ii  = _stitcherView->items();
    QMap<QString,ImageItem *> sortMap;
    for(int i = 0; i<ii.size(); i++) {
        if(ImageItem * imageItem = qgraphicsitem_cast<ImageItem *>(ii[i])) {
            if(imageItem->isVisible()) {
                sortMap.insert(imageItem->identifier(),imageItem);
            }
        }
    }
    QList<ImageItem *>sortedItems = sortMap.values();
    QStandardItemModel * model = qobject_cast<QStandardItemModel *>(geometryTree->model());
    model->clear();
    model->setHorizontalHeaderLabels(QStringList() << "Parameter" << "Value" << "Locked");

    for(int i = 0; i<sortedItems.size(); i++) {
        ImageItem * imageItem = sortedItems[i];
        const QMetaObject *metaobject =  imageItem->metaObject();
        int count = metaobject->propertyCount();
        QStandardItem * itemName = new QStandardItem(imageItem->identifier());
        QStandardItem * itemValue = new QStandardItem();
        QStandardItem * itemLocked = new QStandardItem();
        itemLocked->setFlags(itemLocked->flags() & ~Qt::ItemIsEditable);
        QStandardItem *parentItem = model->invisibleRootItem();
        itemName->setFlags(itemName->flags() & ~Qt::ItemIsEditable);
        itemValue->setFlags(itemValue->flags() & ~Qt::ItemIsEditable);
        if(model->findItems(itemName->text()).empty()) {
            parentItem->appendRow(QList<QStandardItem *>() << itemName <<  itemValue << itemLocked);
            parentItem = itemName;
        } else {
            parentItem = model->findItems(itemName->text()).first();
        }
        for (int j=0; j<count; ++j) {
            QMetaProperty metaproperty = metaobject->property(j);
            const char *name = metaproperty.name();
            if(!QString(name).startsWith(tag)) {
                continue;
            }
            QVariant var =  imageItem->property(name);
            Qt::ItemFlags itemValueFlags = Qt::ItemIsSelectable|Qt::ItemIsEnabled;
            if(metaproperty.isWritable()) {
                itemValueFlags |= Qt::ItemIsEditable;
            }
            if(var.type() == QVariant::Double) {
                double value = var.toDouble();
                if(QString(name).endsWith("_theta") || QString(name).endsWith("_alpha")) {
                    /* convert to degrees */
                    value *= 180/M_PI;
                }
                if(QString(name).endsWith("_dy")) {
                    /* swap axis */
                    value = -value;
                }
                QStandardItem * itemName = new QStandardItem(_stitcherView->propertyNameToDisplayName(name,tag));
                QStandardItem * itemValue = new QStandardItem(QString("%0").arg(value));
                itemValue->setData(value,Qt::UserRole + 1);
                itemValue->setData(QString(name),Qt::UserRole + 2);
                itemValue->setData(QVariant::fromValue(imageItem),Qt::UserRole + 3);
                itemName->setFlags(itemName->flags() & ~Qt::ItemIsEditable);
                itemValue->setFlags(itemValueFlags);
                QStandardItem * itemLocked = new QStandardItem();
                itemLocked->setFlags(itemLocked->flags() & ~Qt::ItemIsEditable);
                /* check for lock property */
                QString lockedPropertyName = name + QString("_locked");
                if(imageItem->property(lockedPropertyName.toAscii().data()).isValid()) {
                    bool locked = imageItem->property(lockedPropertyName.toAscii().data()).toBool();
                    itemLocked->setCheckable(true);
                    itemLocked->setData(locked,Qt::UserRole + 1);
                    itemLocked->setData(QString(lockedPropertyName),Qt::UserRole + 2);
                    itemLocked->setData(QVariant::fromValue(imageItem),Qt::UserRole + 3);
                    if(locked) {
                        itemLocked->setCheckState(Qt::Checked);
                        itemValue->setEnabled(false);
                    }
                }
                /* Temporarily disable Dz and Alpha */
                if(itemName->text() == "Dz" ||
                        itemName->text() == "Alpha") {
                    itemLocked->setCheckState(Qt::Checked);
                    itemName->setEnabled(false);
                    itemValue->setEnabled(false);
                    itemLocked->setEnabled(false);
                    itemName->setToolTip("Currently disabled");
                    itemValue->setToolTip("Currently disabled");
                    itemLocked->setToolTip("Currently disabled");
                }
                parentItem->appendRow(QList<QStandardItem *>() << itemName << itemValue << itemLocked);
            }
        }
    }
    geometryTree->expandAll();
    geometryTree->resizeColumnToContents(0);
    geometryTree->sortByColumn(0,Qt::AscendingOrder);
}
コード例 #25
0
void Camera_positions_list::addItem(QString text, QString data)
{
  QStandardItem* item = new QStandardItem(text);
  item->setData(data, Qt::UserRole);
  m_model->insertRow(m_model->rowCount(), item);
}
コード例 #26
0
ファイル: thumbview.cpp プロジェクト: JHooverman/phototonic
void ThumbView::addThumb(QString &imageFullPath)
{
	QStandardItem *thumbIitem = new QStandardItem();
	QImageReader thumbReader;
	QSize hintSize;
	QSize currThumbSize;
	static QImage thumb;

	if (GData::thumbsLayout == Squares)
		hintSize = QSize(thumbWidth / 2, thumbWidth / 2);
	else if (GData::thumbsLayout == Classic)
		hintSize = QSize(thumbWidth, thumbHeight + 
							(GData::showLabels? QFontMetrics(font()).height() + 5 : 0));
	
	thumbFileInfo = QFileInfo(imageFullPath);
	thumbIitem->setData(true, LoadedRole);
	thumbIitem->setData(0, SortRole);
	thumbIitem->setData(thumbFileInfo.filePath(), FileNameRole);
	if (GData::thumbsLayout != Squares && GData::showLabels)
		thumbIitem->setData(thumbFileInfo.fileName(), Qt::DisplayRole);

	thumbReader.setFileName(imageFullPath);
	currThumbSize = thumbReader.size();
	if (currThumbSize.isValid())
	{
		if (!GData::noEnlargeSmallThumb
			|| (currThumbSize.width() > thumbWidth || currThumbSize.height() > thumbHeight))
		{
			currThumbSize.scale(QSize(thumbWidth, thumbHeight), Qt::KeepAspectRatio);
		}
			
		thumbReader.setScaledSize(currThumbSize);
		thumb = thumbReader.read();

		if (GData::exifThumbRotationEnabled)
		{
			imageView->rotateByExifRotation(thumb, imageFullPath);
			currThumbSize = thumb.size();
			currThumbSize.scale(QSize(thumbWidth, thumbHeight), Qt::KeepAspectRatio);
		}
			
		thumbIitem->setIcon(QPixmap::fromImage(thumb));
	}
	else
	{
		thumbIitem->setIcon(QIcon::fromTheme("image-missing",
								QIcon(":/images/error_image.png")).pixmap(BAD_IMG_SZ, BAD_IMG_SZ));
		currThumbSize.setHeight(BAD_IMG_SZ);
		currThumbSize.setWidth(BAD_IMG_SZ);
	}

	if (GData::thumbsLayout == Compact)
	{
		if (GData::showLabels)
			currThumbSize.setHeight(currThumbSize.height() + QFontMetrics(font()).height() + 5);
		thumbIitem->setSizeHint(currThumbSize);
	}
	else
		thumbIitem->setSizeHint(hintSize);

	thumbViewModel->appendRow(thumbIitem);
}
コード例 #27
0
void PreferencesDialog::InitWaveInfo()
{
    QHash<MachineType, int> toprows;

    waveModel->clear();
    machlevel.clear();
    toprows.clear();
    QStringList headers;
    headers.append(tr("Name"));
    headers.append(tr("Color"));
    headers.append(tr("Overview"));
    headers.append(tr("Lower"));
    headers.append(tr("Upper"));
    headers.append(tr("Label"));
    headers.append(tr("Details"));
    waveModel->setHorizontalHeaderLabels(headers);
    ui->waveView->setColumnWidth(0, 200);
    ui->waveView->setColumnWidth(1, 40);
    ui->waveView->setColumnWidth(2, 60);
    ui->waveView->setColumnWidth(3, 50);
    ui->waveView->setColumnWidth(4, 50);
    ui->waveView->setColumnWidth(5, 100);
    ui->waveView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->waveView->setSelectionBehavior(QAbstractItemView::SelectItems);

    waveModel->setColumnCount(7);

    QStandardItem *hdr = nullptr;

    QMap<MachineType, QString> Section;

    Section[MT_CPAP] = tr("CPAP Waveforms");
    Section[MT_OXIMETER] = tr("Oximeter Waveforms");
    Section[MT_POSITION] = tr("Positional Waveforms");
    Section[MT_SLEEPSTAGE] = tr("Sleep Stage Waveforms");

    QMap<MachineType, QString>::iterator it;

    for (it = Section.begin(); it != Section.end(); ++it) {
        machlevel[it.key()] = hdr = new QStandardItem(it.value());
        hdr->setEditable(false);
        QList<QStandardItem *> list;
        list.append(hdr);
        for (int i=0; i<6; i++) {
            QStandardItem *it = new QStandardItem();
            it->setEnabled(false);
            list.append(it);
        }
        waveModel->appendRow(list);
    }

    ui->waveView->setAlternatingRowColors(true);

    // ui->graphView->setFirstColumnSpanned(0,daily->index(),true); // Crashes on windows.. Why do I need this again?

    QHash<QString, schema::Channel *>::iterator ci;

    SpinBoxDelegate * spinbox = new SpinBoxDelegate(ui->waveView);

    ui->waveView->setItemDelegateForColumn(3,spinbox);
    ui->waveView->setItemDelegateForColumn(4,spinbox);

    int row = 0;
    for (ci = schema::channel.names.begin(); ci != schema::channel.names.end(); ci++) {
        schema::Channel * chan = ci.value();
        if (chan->type() != schema::WAVEFORM) continue;

        QList<QStandardItem *> items;
        QStandardItem *it = new QStandardItem(chan->fullname());

        it->setCheckable(true);
        it->setCheckState(chan->enabled() ? Qt::Checked : Qt::Unchecked);
        it->setEditable(true);
        it->setData(chan->id(), Qt::UserRole);
        it->setToolTip(tr("Double click to change the descriptive name this channel."));
        items.push_back(it);

        it = new QStandardItem();
        it->setBackground(QBrush(chan->defaultColor()));
        it->setEditable(false);
        it->setData(chan->defaultColor().rgba(), Qt::UserRole);
        it->setToolTip(tr("Double click to change the default color for this channel plot/flag/data."));
        it->setSelectable(false);
        items.push_back(it);

        it = new QStandardItem();
        it->setCheckable(true);
        it->setCheckState(chan->showInOverview() ? Qt::Checked : Qt::Unchecked);
        it->setEditable(true);
        it->setData(chan->id(), Qt::UserRole);
        it->setToolTip(tr("Whether a breakdown of this waveform displays in overview."));
        items.push_back(it);


        it = new QStandardItem(QString::number(chan->lowerThreshold(),'f',1));
        it->setToolTip(tr("Here you can set the <b>lower</b> threshold used for certain calculations on the %1 waveform").arg(chan->fullname()));
        it->setEditable(true);
        items.push_back(it);

        it = new QStandardItem(QString::number(chan->upperThreshold(),'f',1));
        it->setToolTip(tr("Here you can set the <b>upper</b> threshold used for certain calculations on the %1 waveform").arg(chan->fullname()));
        it->setEditable(true);
        items.push_back(it);

        it = new QStandardItem(chan->label());
        it->setToolTip(tr("This is the short-form label to indicate this channel on screen."));

        it->setEditable(true);
        items.push_back(it);

        it = new QStandardItem(chan->description());
        it->setToolTip(tr("This is a description of what this channel does."));

        it->setEditable(true);
        items.push_back(it);

        row = toprows[chan->machtype()]++;
        machlevel[chan->machtype()]->insertRow(row, items);
    }

    for(QHash<MachineType, QStandardItem *>::iterator i = machlevel.begin(); i != machlevel.end(); ++i) {
        if (i.value()->rowCount() == 0) {
            waveModel->removeRow(i.value()->row());
        }
    }

    ui->waveView->expandAll();
    ui->waveView->setSortingEnabled(true);
}
コード例 #28
0
ファイル: qgspgtablemodel.cpp プロジェクト: exlimit/QGIS
bool QgsPgTableModel::setData( const QModelIndex &idx, const QVariant &value, int role )
{
  if ( !QStandardItemModel::setData( idx, value, role ) )
    return false;

  if ( idx.column() == DbtmType || idx.column() == DbtmSrid || idx.column() == DbtmPkCol )
  {
    QgsWkbTypes::Type wkbType = ( QgsWkbTypes::Type ) idx.sibling( idx.row(), DbtmType ).data( Qt::UserRole + 2 ).toInt();

    QString tip;
    if ( wkbType == QgsWkbTypes::Unknown )
    {
      tip = tr( "Specify a geometry type in the '%1' column" ).arg( tr( "Data Type" ) );
    }
    else if ( wkbType != QgsWkbTypes::NoGeometry )
    {
      bool ok;
      int srid = idx.sibling( idx.row(), DbtmSrid ).data().toInt( &ok );

      if ( !ok || srid == INT_MIN )
        tip = tr( "Enter a SRID into the '%1' column" ).arg( tr( "SRID" ) );
    }

    QStringList pkCols = idx.sibling( idx.row(), DbtmPkCol ).data( Qt::UserRole + 1 ).toStringList();
    if ( tip.isEmpty() && !pkCols.isEmpty() )
    {
      QSet<QString> s0( idx.sibling( idx.row(), DbtmPkCol ).data( Qt::UserRole + 2 ).toStringList().toSet() );
      QSet<QString> s1( pkCols.toSet() );
      if ( s0.intersect( s1 ).isEmpty() )
        tip = tr( "Select columns in the '%1' column that uniquely identify features of this layer" ).arg( tr( "Feature id" ) );
    }

    for ( int i = 0; i < DbtmColumns; i++ )
    {
      QStandardItem *item = itemFromIndex( idx.sibling( idx.row(), i ) );
      if ( tip.isEmpty() )
      {
        if ( i == DbtmSchema )
        {
          item->setData( QVariant(), Qt::DecorationRole );
        }

        item->setFlags( item->flags() | Qt::ItemIsSelectable );
        item->setToolTip( QLatin1String( "" ) );
      }
      else
      {
        item->setFlags( item->flags() & ~Qt::ItemIsSelectable );

        if ( i == DbtmSchema )
          item->setData( QgsApplication::getThemeIcon( QStringLiteral( "/mIconWarning.svg" ) ), Qt::DecorationRole );

        if ( i == DbtmSchema || i == DbtmTable || i == DbtmGeomCol )
        {
          item->setFlags( item->flags() );
          item->setToolTip( tip );
        }
      }
    }
  }

  return true;
}
コード例 #29
0
    void UpdaterDialog::initModel(QJsonObject json)
    {
        model = new QStandardItemModel(0,4,this);

        /**
         * @brief jsonObject has the following item structure:
         *
         *   {...},
         *   {
         *     "wpnxmscp": {
         *       "latest": {
         *           "url": "https://github.com/WPN-XM/../file.zip",
         *           "version": "0.8.4"
         *       },
         *       "name": "WPN-XM Server Control Panel x86",
         *       "website": "http://wpn-xm.org/"
         *   },
         *   {...}
         */

        /**
         * populate Model with JSON data
         */
        for (QJsonObject:: Iterator iter = json.begin(); iter != json.end(); ++iter)
        {
            QList<QStandardItem*> rowItems;

            // The "key" is the registry name of the software component.
            //QString *registrySoftwareName = QString(iter.key());

            // The "value" is the data of the software component
            QJsonObject software = iter.value().toObject();

            // Map for Latest URL and Version
            QVariantMap latestVersionMap = software["latest"].toObject().toVariantMap();
            //qDebug() << latestVersion["url"].toString() << latestVersion["version"].toString();

            // Table Columns

            // Software Name
            QStandardItem *softwareName = new QStandardItem( "      " + software["name"].toString() );
            rowItems.append(softwareName);

            // Website Link
            QStandardItem *websiteURL = new QStandardItem( software["website"].toString() );
            rowItems.append(websiteURL);

            // Installed Version (= Your current version)
            QString installedVersionString = "1.2.3"; // TODO: detect currently installed versions
            QStandardItem *installedVersion = new QStandardItem( installedVersionString );
            installedVersion->setTextAlignment(Qt::AlignCenter);
            rowItems.append(installedVersion);

            // Latest Version
            QStandardItem *latestVersion = new QStandardItem( latestVersionMap["version"].toString() );
            latestVersion->setTextAlignment(Qt::AlignCenter);
            rowItems.append(latestVersion);

            // Download URL for Latest Version
            QStandardItem *latestVersionURL = new QStandardItem( latestVersionMap["url"].toString() );
            rowItems.append(latestVersionURL);

            // Action

            /**
             * How to render widgets in a table cell when using QTableView?
             *
             * Setting a QPushButton directly to the model is not possible at this point.
             * But its possible to set the model to the tableView and then use rowCount()
             * and draw the buttons using setIndexWidet() in a second iteration.
             *
             * Boils down to: When using a
             * - tableWidget: ugly sorting, no-model, but full cell control with all widgets
             * - tableView: either nice sorting, less cell control, no widgets, but a proper model
             *
             * ----------
             * Finally, i came up with using an ItemDelegate to render the widgets in the action column.
             * The rendering is done by the delegate's paint function.
             * To render multiple widgets (Download Button, Download ProgressBar, Install Button)
             * i've added a custom UserRole "WidgetRole" and three Roles:
             * DownloadPushButton, DownloadProgressBar, InstallPushButton.
             * These roles are set as data to the model and tell the view what to render.
             * This allows to easily update the model and get the matching widgets based on the role.
             */
            QStandardItem *action = new QStandardItem("ActionCell");
            action->setData(ActionColumnItemDelegate::DownloadPushButton, ActionColumnItemDelegate::WidgetRole);
            rowItems.append(action);

            model->appendRow(rowItems);            
        }

        /**
         * Set Header Labels for Table
         */
        QStringList headerLabels;
        // Table               1              (hidden)           2               3             (hidden)        4
        headerLabels<<"Software Component"<<"WebsiteURL"<<"Your Version"<<"Latest Version"<<"DownloadURL"<<"Actions";
        model->setHorizontalHeaderLabels(headerLabels);

        /**
         * Setup SortingProxy for the Model
         */
        sortFilterProxyModel = new QSortFilterProxyModel(this);
        sortFilterProxyModel->setSourceModel(model);
        // sorting is case-insensitive
        sortFilterProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
        // filtering is case-insensitive and using the software name column
        sortFilterProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
        sortFilterProxyModel->setFilterKeyColumn(Columns::SoftwareComponent);
    }
コード例 #30
0
void ObservingList::slotAddObject( SkyObject *obj, bool session, bool update ) {
    bool addToWishList=true;
    if( ! obj )
        obj = ks->map()->clickedObject();

    if( obj->name() == "star" ) {
        KMessageBox::sorry(0, i18n( "Unnamed stars are not supported in the observing lists"));
        return;
    }
        
    //First, make sure object is not already in the list
    if ( obsList().contains( obj ) ) {
        addToWishList = false;
        if( ! session ) {
            ks->statusBar()->changeItem( i18n( "%1 is already in your wishlist.", obj->name() ), 0 );
            return;
        }
    }

    if ( session && sessionList().contains( obj ) ) { 
        ks->statusBar()->changeItem( i18n( "%1 is already in the session plan.", obj->name() ), 0 );
        return;
    }
    
    QString smag = "--";
    if (  - 30.0 < obj->mag() && obj->mag() < 90.0 )
        smag = QString::number( obj->mag(), 'g', 2 ); // The lower limit to avoid display of unrealistic comet magnitudes

    SkyPoint p = obj->recomputeCoords( dt, geo );

    //Insert object in the Wish List
    if( addToWishList  ) {
        m_ObservingList.append( obj );
        m_CurrentObject = obj;
        QList<QStandardItem*> itemList;

        QString ra, dec;

        if(obj->name() == "star" ) {
            ra = obj->ra0().toHMSString();
            dec = obj->dec0().toDMSString();
        }
        else {
            ra = p.ra().toHMSString();
            dec = p.dec().toDMSString();
        }

        itemList << new QStandardItem( obj->translatedName() )
                << new QStandardItem( ra )
                << new QStandardItem( dec )
                << new QStandardItem( smag )
                << new QStandardItem( obj->typeName() );

        m_Model->appendRow( itemList );
        //Note addition in statusbar
        ks->statusBar()->changeItem( i18n( "Added %1 to observing list.", obj->name() ), 0 );
        ui->TableView->resizeColumnsToContents(); 
        if( ! update ) slotSaveList();
    }
    //Insert object in the Session List
    if( session ){
        m_SessionList.append(obj);
        dt.setTime( TimeHash.value( obj->name(), obj->transitTime( dt, geo ) ) );
        dms lst(geo->GSTtoLST( dt.gst() ));
        p.EquatorialToHorizontal( &lst, geo->lat() );
        QList<QStandardItem*> itemList;

        QString ra, dec, time = "--", alt = "--", az = "--";

        QStandardItem *BestTime = new QStandardItem();
        if(obj->name() == "star" ) {
            ra = obj->ra0().toHMSString();
            dec = obj->dec0().toDMSString();
            BestTime->setData( QString( "--" ), Qt::DisplayRole );
        }
        else {
            ra = p.ra().toHMSString();
            dec = p.dec().toDMSString();
            BestTime->setData( TimeHash.value( obj->name(), obj->transitTime( dt, geo ) ), Qt::DisplayRole );
            alt = p.alt().toDMSString();
            az = p.az().toDMSString();
        }
        // TODO: Change the rest of the parameters to their appropriate datatypes.
        itemList << new QStandardItem( obj->translatedName() )
                << new QStandardItem( ra )
                << new QStandardItem( dec )
                << new QStandardItem( smag )
                << new QStandardItem( obj->typeName() )
                << BestTime
                << new QStandardItem( alt )
                << new QStandardItem( az );

        m_Session->appendRow( itemList );
        //Adding an object should trigger the modified flag
        isModified = true;
        ui->SessionView->resizeColumnsToContents();
        //Note addition in statusbar
        ks->statusBar()->changeItem( i18n( "Added %1 to session list.", obj->name() ), 0 );
    }
    setSaveImagesButton();
}