void DrawingView::printPdf() { Gui::FileOptionsDialog dlg(this, 0); dlg.setFileMode(QFileDialog::AnyFile); dlg.setAcceptMode(QFileDialog::AcceptSave); dlg.setWindowTitle(tr("Export PDF")); dlg.setFilters(QStringList() << tr("PDF file (*.pdf)")); QGridLayout *gridLayout; QGridLayout *formLayout; QGroupBox *groupBox; QListWidget *listWidget; QListWidgetItem* item; QWidget *form = new QWidget(&dlg); form->resize(40, 300); formLayout = new QGridLayout(form); groupBox = new QGroupBox(form); gridLayout = new QGridLayout(groupBox); listWidget = new QListWidget(groupBox); gridLayout->addWidget(listWidget, 0, 0, 1, 1); formLayout->addWidget(groupBox, 0, 0, 1, 1); groupBox->setTitle(tr("Page sizes")); item = new QListWidgetItem(tr("A0"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A0)); item = new QListWidgetItem(tr("A1"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A1)); item = new QListWidgetItem(tr("A2"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A2)); item = new QListWidgetItem(tr("A3"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A3)); item = new QListWidgetItem(tr("A4"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A4)); item = new QListWidgetItem(tr("A5"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A5)); int index = 4; // by default A4 for (int i=0; i<listWidget->count(); i++) { if (listWidget->item(i)->data(Qt::UserRole).toInt() == m_pageSize) { index = i; break; } } listWidget->item(index)->setSelected(true); dlg.setOptionsWidget(Gui::FileOptionsDialog::ExtensionRight, form, false); if (dlg.exec() == QDialog::Accepted) { Gui::WaitCursor wc; QString filename = dlg.selectedFiles().front(); QPrinter printer(QPrinter::HighResolution); printer.setFullPage(true); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(filename); printer.setOrientation(m_orientation); QList<QListWidgetItem*> items = listWidget->selectedItems(); if (items.size() == 1) { int AX = items.front()->data(Qt::UserRole).toInt(); printer.setPaperSize(QPrinter::PageSize(AX)); } print(&printer); } }
void QgsLayerStylingWidget::setLayer( QgsMapLayer *layer ) { if ( layer == mCurrentLayer ) return; if ( mCurrentLayer ) { disconnect( mCurrentLayer, SIGNAL( styleChanged() ), this, SLOT( updateCurrentWidgetLayer() ) ); } if ( !layer || !layer->isSpatial() ) { mLayerCombo->setLayer( nullptr ); mStackedWidget->setCurrentIndex( mNotSupportedPage ); mLastStyleXml.clear(); mCurrentLayer = nullptr; return; } bool sameLayerType = false; if ( mCurrentLayer ) { sameLayerType = mCurrentLayer->type() == layer->type(); } mCurrentLayer = layer; mUndoWidget->setUndoStack( layer->undoStackStyles() ); connect( mCurrentLayer, SIGNAL( styleChanged() ), this, SLOT( updateCurrentWidgetLayer() ) ); int lastPage = mOptionsListWidget->currentIndex().row(); mOptionsListWidget->blockSignals( true ); mOptionsListWidget->clear(); mUserPages.clear(); if ( layer->type() == QgsMapLayer::VectorLayer ) { QListWidgetItem* symbolItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/symbology.svg" ), QString() ); symbolItem->setData( Qt::UserRole, Symbology ); symbolItem->setToolTip( tr( "Symbology" ) ); mOptionsListWidget->addItem( symbolItem ); QListWidgetItem* labelItem = new QListWidgetItem( QgsApplication::getThemeIcon( "labelingSingle.svg" ), QString() ); labelItem->setData( Qt::UserRole, VectorLabeling ); labelItem->setToolTip( tr( "Labels" ) ); mOptionsListWidget->addItem( labelItem ); } else if ( layer->type() == QgsMapLayer::RasterLayer ) { QListWidgetItem* symbolItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/symbology.svg" ), QString() ); symbolItem->setData( Qt::UserRole, Symbology ); symbolItem->setToolTip( tr( "Symbology" ) ); mOptionsListWidget->addItem( symbolItem ); QListWidgetItem* transparencyItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/transparency.png" ), QString() ); transparencyItem->setToolTip( tr( "Transparency" ) ); transparencyItem->setData( Qt::UserRole, RasterTransparency ); mOptionsListWidget->addItem( transparencyItem ); if ( static_cast<QgsRasterLayer*>( layer )->dataProvider()->capabilities() & QgsRasterDataProvider::Size ) { QListWidgetItem* histogramItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/histogram.png" ), QString() ); histogramItem->setData( Qt::UserRole, RasterHistogram ); mOptionsListWidget->addItem( histogramItem ); histogramItem->setToolTip( tr( "Histogram" ) ); } } Q_FOREACH ( QgsMapLayerConfigWidgetFactory* factory, mPageFactories ) { if ( factory->supportsStyleDock() && factory->supportsLayer( layer ) ) { QListWidgetItem* item = new QListWidgetItem( factory->icon(), QString() ); item->setToolTip( factory->title() ); mOptionsListWidget->addItem( item ); int row = mOptionsListWidget->row( item ); mUserPages[row] = factory; } } QListWidgetItem* historyItem = new QListWidgetItem( QgsApplication::getThemeIcon( "mActionHistory.svg" ), QString() ); historyItem->setData( Qt::UserRole, History ); historyItem->setToolTip( tr( "History" ) ); mOptionsListWidget->addItem( historyItem ); mOptionsListWidget->blockSignals( false ); if ( sameLayerType ) { mOptionsListWidget->setCurrentRow( lastPage ); } else { mOptionsListWidget->setCurrentRow( 0 ); } mStackedWidget->setCurrentIndex( 1 ); QString errorMsg; QDomDocument doc( "style" ); mLastStyleXml = doc.createElement( "style" ); doc.appendChild( mLastStyleXml ); mCurrentLayer->writeStyle( mLastStyleXml, doc, errorMsg ); }
/************************************************ * Widget Listing: * Creation of the list of drawed lovely buttons ************************************************/ WidgetListing::WidgetListing( intf_thread_t *p_intf, QWidget *_parent ) : QListWidget( _parent ) { /* We need the parent to know the options checked */ parent = qobject_cast<ToolbarEditDialog *>(_parent); assert( parent ); /* Normal options */ setViewMode( QListView::ListMode ); setTextElideMode( Qt::ElideNone ); setDragEnabled( true ); int icon_size = fontMetrics().height(); setIconSize( QSize( icon_size * 2, icon_size ) ); /* All the buttons do not need a special rendering */ for( int i = 0; i < BUTTON_MAX; i++ ) { QListWidgetItem *widgetItem = new QListWidgetItem( this ); widgetItem->setText( qtr( nameL[i] ) ); widgetItem->setSizeHint( QSize( widgetItem->sizeHint().width(), 32 ) ); widgetItem->setIcon( QIcon( iconL[i] ) ); widgetItem->setData( Qt::UserRole, QVariant( i ) ); widgetItem->setToolTip( widgetItem->text() ); addItem( widgetItem ); } /* Spacers are yet again a different thing */ QListWidgetItem *widgetItem = new QListWidgetItem( QIcon( ":/toolbar/space.svg" ), qtr( "Spacer" ), this ); widgetItem->setData( Qt::UserRole, WIDGET_SPACER ); widgetItem->setToolTip( widgetItem->text() ); widgetItem->setSizeHint( QSize( widgetItem->sizeHint().width(), 32 ) ); addItem( widgetItem ); widgetItem = new QListWidgetItem( QIcon( ":/toolbar/space.svg" ), qtr( "Expanding Spacer" ), this ); widgetItem->setData( Qt::UserRole, WIDGET_SPACER_EXTEND ); widgetItem->setToolTip( widgetItem->text() ); widgetItem->setSizeHint( QSize( widgetItem->sizeHint().width(), 32 ) ); addItem( widgetItem ); /** * For all other widgets, we create then, do a pseudo rendering in * a pixmaps for the view, and delete the object * * A lot of code is retaken from the Abstract, but not exactly... * So, rewrite. * They are better ways to deal with this, but I doubt that this is * necessary. If you feel like you have the time, be my guest. * -- * jb **/ for( int i = SPLITTER; i < SPECIAL_MAX; i++ ) { QWidget *widget = NULL; QListWidgetItem *widgetItem = new QListWidgetItem; widgetItem->setSizeHint( QSize( widgetItem->sizeHint().width(), 32 ) ); switch( i ) { case SPLITTER: { QFrame *line = new QFrame( this ); line->setFrameShape( QFrame::VLine ); line->setFrameShadow( QFrame::Raised ); line->setLineWidth( 0 ); line->setMidLineWidth( 1 ); widget = line; } widgetItem->setText( qtr("Splitter") ); break; case INPUT_SLIDER: { SeekSlider *slider = new SeekSlider( p_intf, Qt::Horizontal, this ); widget = slider; } widgetItem->setText( qtr("Time Slider") ); break; case VOLUME: { SoundWidget *snd = new SoundWidget( this, p_intf, parent->getOptions() & WIDGET_SHINY ); widget = snd; } widgetItem->setText( qtr("Volume") ); break; case VOLUME_SPECIAL: { QListWidgetItem *widgetItem = new QListWidgetItem( this ); widgetItem->setText( qtr("Small Volume") ); widgetItem->setIcon( QIcon( ":/toolbar/volume-medium.svg" ) ); widgetItem->setData( Qt::UserRole, QVariant( i ) ); addItem( widgetItem ); } continue; case TIME_LABEL: { QLabel *timeLabel = new QLabel( "12:42/2:12:42", this ); widget = timeLabel; } widgetItem->setText( qtr("Time") ); break; case MENU_BUTTONS: { QWidget *discFrame = new QWidget( this ); //discFrame->setLineWidth( 1 ); QHBoxLayout *discLayout = new QHBoxLayout( discFrame ); discLayout->setSpacing( 0 ); discLayout->setMargin( 0 ); QToolButton *prevSectionButton = new QToolButton( discFrame ); prevSectionButton->setIcon( QIcon( ":/toolbar/dvd_prev.svg" ) ); prevSectionButton->setToolTip( qtr("Previous Chapter/Title" ) ); discLayout->addWidget( prevSectionButton ); QToolButton *nextButton = new QToolButton( discFrame ); nextButton->setIcon( QIcon( ":/toolbar/dvd_next.svg" ) ); nextButton->setToolTip( qtr("Next Chapter/Title" ) ); discLayout->addWidget( nextButton ); QToolButton *menuButton = new QToolButton( discFrame ); menuButton->setIcon( QIcon( ":/toolbar/dvd_menu.svg" ) ); menuButton->setToolTip( qtr( "Menu" ) ); discLayout->addWidget( menuButton ); widget = discFrame; } widgetItem->setText( qtr("DVD menus") ); break; case TELETEXT_BUTTONS: { QWidget *telexFrame = new QWidget( this ); QHBoxLayout *telexLayout = new QHBoxLayout( telexFrame ); telexLayout->setSpacing( 0 ); telexLayout->setMargin( 0 ); QToolButton *telexOn = new QToolButton( telexFrame ); telexOn->setIcon( QIcon( ":/toolbar/tv.svg" ) ); telexLayout->addWidget( telexOn ); QToolButton *telexTransparent = new QToolButton; telexTransparent->setIcon( QIcon( ":/toolbar/tvtelx.svg" ) ); telexTransparent->setToolTip( qtr("Teletext transparency") ); telexLayout->addWidget( telexTransparent ); QSpinBox *telexPage = new QSpinBox; telexLayout->addWidget( telexPage ); widget = telexFrame; } widgetItem->setText( qtr("Teletext") ); break; case ADVANCED_CONTROLLER: { AdvControlsWidget *advControls = new AdvControlsWidget( p_intf, this ); widget = advControls; } widgetItem->setText( qtr("Advanced Buttons") ); break; case PLAYBACK_BUTTONS: { widget = new QWidget; DeckButtonsLayout *layout = new DeckButtonsLayout( widget ); BrowseButton *prev = new BrowseButton( widget, BrowseButton::Backward ); BrowseButton *next = new BrowseButton( widget ); RoundButton *play = new RoundButton( widget ); layout->setBackwardButton( prev ); layout->setForwardButton( next ); layout->setRoundButton( play ); } widgetItem->setText( qtr("Playback Buttons") ); break; case ASPECT_RATIO_COMBOBOX: widget = new AspectRatioComboBox( p_intf, THEMIM->getAspectRatio() ); widgetItem->setText( qtr("Aspect ratio selector") ); break; case SPEED_LABEL: widget = new SpeedLabel( p_intf, this ); widgetItem->setText( qtr("Speed selector") ); break; case TIME_LABEL_ELAPSED: widget = new QLabel( "2:42", this ); widgetItem->setText( qtr("Elapsed time") ); break; case TIME_LABEL_REMAINING: widget = new QLabel( "-2:42", this ); widgetItem->setText( qtr("Total/Remaining time") ); break; default: msg_Warn( p_intf, "This should not happen %i", i ); break; } if( widget == NULL ) continue; widgetItem->setIcon( QIcon( widget->grab() ) ); widgetItem->setToolTip( widgetItem->text() ); widget->hide(); widgetItem->setData( Qt::UserRole, QVariant( i ) ); addItem( widgetItem ); delete widget; } }
StatusFilterWidget::StatusFilterWidget(QWidget *parent, TransferListWidget *transferList) : BaseFilterWidget(parent, transferList) { connect(BitTorrent::Session::instance(), &BitTorrent::Session::torrentsUpdated , this, &StatusFilterWidget::updateTorrentNumbers); // Add status filters QListWidgetItem *all = new QListWidgetItem(this); all->setData(Qt::DisplayRole, QVariant(tr("All (0)", "this is for the status filter"))); all->setData(Qt::DecorationRole, QIcon(":/icons/skin/filterall.svg")); QListWidgetItem *downloading = new QListWidgetItem(this); downloading->setData(Qt::DisplayRole, QVariant(tr("Downloading (0)"))); downloading->setData(Qt::DecorationRole, QIcon(":/icons/skin/downloading.svg")); QListWidgetItem *seeding = new QListWidgetItem(this); seeding->setData(Qt::DisplayRole, QVariant(tr("Seeding (0)"))); seeding->setData(Qt::DecorationRole, QIcon(":/icons/skin/uploading.svg")); QListWidgetItem *completed = new QListWidgetItem(this); completed->setData(Qt::DisplayRole, QVariant(tr("Completed (0)"))); completed->setData(Qt::DecorationRole, QIcon(":/icons/skin/completed.svg")); QListWidgetItem *resumed = new QListWidgetItem(this); resumed->setData(Qt::DisplayRole, QVariant(tr("Resumed (0)"))); resumed->setData(Qt::DecorationRole, QIcon(":/icons/skin/resumed.svg")); QListWidgetItem *paused = new QListWidgetItem(this); paused->setData(Qt::DisplayRole, QVariant(tr("Paused (0)"))); paused->setData(Qt::DecorationRole, QIcon(":/icons/skin/paused.svg")); QListWidgetItem *active = new QListWidgetItem(this); active->setData(Qt::DisplayRole, QVariant(tr("Active (0)"))); active->setData(Qt::DecorationRole, QIcon(":/icons/skin/filteractive.svg")); QListWidgetItem *inactive = new QListWidgetItem(this); inactive->setData(Qt::DisplayRole, QVariant(tr("Inactive (0)"))); inactive->setData(Qt::DecorationRole, QIcon(":/icons/skin/filterinactive.svg")); QListWidgetItem *errored = new QListWidgetItem(this); errored->setData(Qt::DisplayRole, QVariant(tr("Errored (0)"))); errored->setData(Qt::DecorationRole, QIcon(":/icons/skin/error.svg")); const Preferences *const pref = Preferences::instance(); setCurrentRow(pref->getTransSelFilter(), QItemSelectionModel::SelectCurrent); toggleFilter(pref->getStatusFilterState()); }
void TriangulationSidebar::addPoint(QPointF point) { QString str=QString::number(point.y())+", "+QString::number(point.x()); QListWidgetItem *item = new QListWidgetItem(str); item->setData(Qt::UserRole, QVariant(point)); pointsListWidget->addItem(item); }
//XML //Parse XML into tasklist form int TaskList_Main::parseXML(QDomDocument &domTree){ QDomElement set = domTree.namedItem("listset").toElement(); QMessageBox msgBox; //If tree doesn't exist, stop if(set.isNull()){ msgBox.setText("No <listset> element at top level"); msgBox.setWindowTitle("Erorr parsing XML"); msgBox.exec(); return -1; } //Iterate through all "list" items QDomElement n = set.firstChildElement("list"); for( ; !n.isNull(); n = n.nextSiblingElement("list")){ emit createList(n.namedItem("list_title").toElement().text()); delListAction->setEnabled(true); printAction->setEnabled(true); printAllAction->setEnabled(true); //Iterate through all "task" items part of "list" QDomElement o = n.firstChildElement("task"); for( ; !o.isNull(); o = o.nextSiblingElement("task")){ my_listwidget *currList = notePane->listMap[notePane->currList]; QListWidgetItem *currItem; QString tempStr; //If task is 'main' (not subtext/subnote) if(o.attribute("task_type") == "main"){ //Change task name notePane->addItemAction(o.namedItem("task_title").toElement().text(), false); currItem = currList->currentItem(); //Change task check state tempStr = o.namedItem("task_check").toElement().text(); if(tempStr == "unchecked") currItem->setCheckState(Qt::Unchecked); else if (tempStr == "checked") currItem->setCheckState(Qt::Checked); else if (tempStr == "part_check") currItem->setCheckState(Qt::PartiallyChecked); else{ msgBox.setText("Unknown check state"); msgBox.setWindowTitle("Erorr parsing XML"); msgBox.exec(); return -1; } //Change task subnote currItem->setData(32, QVariant( o.namedItem("task_note").toElement().text())); //Change if task subnote is displayed tempStr = o.namedItem("task_display").toElement().text(); if(tempStr == "false"){ currItem->setData(33, QVariant(false)); currItem->setData(35, QVariant(false)); } else if(tempStr == "true"){ currItem->setData(33, QVariant(true)); currItem->setData(35, QVariant(true)); } else{ msgBox.setText("Unknown bool type - display"); msgBox.setWindowTitle("Erorr parsing XML"); msgBox.exec(); return -1; } //Change the task due date tempStr = o.namedItem("task_date").toElement().text(); qDebug((const char *)tempStr.toAscii().data()); QDate tempDate; int year = tempStr.left(4).toInt(); int month = tempStr.mid(5, 2).toInt(); int day = tempStr.right(2).toInt(); tempDate.setDate(year, month, day); if(!tempDate.isValid()){ msgBox.setText("Unknown date type"); msgBox.setWindowTitle("Erorr parsing XML"); msgBox.exec(); return -1; } currItem->setData(34, QVariant(tempDate)); //Change the task font tempStr = o.namedItem("task_font").toElement().text(); QFont tempFont; if(!tempFont.fromString(tempStr)){ msgBox.setText("Unknown font"); msgBox.setWindowTitle("Erorr parsing XML"); msgBox.exec(); return -1; } currItem->setFont(tempFont); } //Else if it is a subtext/subnote for a 'main' else if (o.attribute("task_type") == "sub"){ //Change note's text notePane->addItemAction(o.namedItem("task_title").toElement().text(), true); currItem = currList->currentItem(); currItem->setFlags(0); //Change note's font tempStr = o.namedItem("task_font").toElement().text(); QFont tempFont; if(!tempFont.fromString(tempStr)){ msgBox.setText("Unknown font"); msgBox.setWindowTitle("Erorr parsing XML"); msgBox.exec(); return -1; } currItem->setFont(tempFont); } //Else, exit gracefully else{ msgBox.setText("Unknown list type"); msgBox.setWindowTitle("Erorr parsing XML"); msgBox.exec(); return -1; } //Synchronize the option pane optionPane->itemSelectDataIn(*currItem); } } return 0; }
TextPalette::TextPalette(QWidget* parent) : QWidget(parent) { setWindowFlags(Qt::Tool); setupUi(this); pCommon = new Palette; pCommon->setMag(0.8); pCommon->setGrid(33, 60); pCommon->setReadOnly(true); pSmufl = new Palette; pSmufl->setMag(0.8); pSmufl->setGrid(33, 60); pSmufl->setReadOnly(true); pUnicode = new Palette; pUnicode->setMag(0.8); pUnicode->setGrid(33, 60); pUnicode->setReadOnly(true); PaletteScrollArea* psa = new PaletteScrollArea(pCommon); psa->setRestrictHeight(false); tabWidget->clear(); tabWidget->addTab(psa, tr("Common Symbols")); psa = new PaletteScrollArea(pSmufl); psa->setRestrictHeight(false); QSplitter* ws = new QSplitter; lws = new QListWidget; ScoreFont* scoreFont = ScoreFont::fontFactory("Bravura"); QFile fi(scoreFont->fontPath() + "ranges.json"); if (!fi.open(QIODevice::ReadOnly)) qDebug("ScoreFont: open ranges file <%s> failed", qPrintable(fi.fileName())); QJsonParseError error; QJsonObject o = QJsonDocument::fromJson(fi.readAll(), &error).object(); if (error.error != QJsonParseError::NoError) qDebug("Json parse error in <%s>(offset: %d): %s", qPrintable(fi.fileName()), error.offset, qPrintable(error.errorString())); int i = 0; QStringList smuflRangeNames; for (auto s : o.keys()) { QJsonObject range = o.value(s).toObject(); QString desc = range.value("description").toString(); QJsonArray glyphs = range.value("glyphs").toArray(); if (glyphs.size() > 0) { for (QJsonValue g : glyphs) smuflMap[i].append(g.toString()); smuflRangeNames.append(desc); i++; } } lws->addItems(smuflRangeNames); lws->setCurrentRow(0); ws->addWidget(lws); ws->addWidget(psa); tabWidget->addTab(ws, tr("Musical Symbols")); psa = new PaletteScrollArea(pUnicode); psa->setRestrictHeight(false); QSplitter* wu = new QSplitter; lwu = new QListWidget; lwu->setSortingEnabled(true); for (i = 0; i < unicodeRangeNames.length(); i++) { QListWidgetItem* newItem = new QListWidgetItem(qApp->translate("accidental", unicodeRangeNames.at(i).toUtf8().constData())); newItem->setData(Qt::UserRole, i); lwu->addItem(newItem); if (i == 0) lwu->setCurrentItem(newItem); } wu->addWidget(lwu); wu->addWidget(psa); tabWidget->addTab(wu, tr("Unicode Symbols")); connect(lws, SIGNAL(currentRowChanged(int)), SLOT(populateSmufl())); connect(lwu, SIGNAL(currentRowChanged(int)), SLOT(populateUnicode())); // others are done in setFont populateSmufl(); setFocusPolicy(Qt::NoFocus); }
int QgsComposerPictureWidget::addDirectoryToPreview( const QString& path ) { //go through all files of a directory QDir directory( path ); if ( !directory.exists() || !directory.isReadable() ) { return 1; //error } QFileInfoList fileList = directory.entryInfoList( QDir::Files ); QFileInfoList::const_iterator fileIt = fileList.constBegin(); QProgressDialog progress( "Adding Icons...", "Abort", 0, fileList.size() - 1, this ); //cancel button does not seem to work properly with modal dialog //progress.setWindowModality(Qt::WindowModal); int counter = 0; for ( ; fileIt != fileList.constEnd(); ++fileIt ) { progress.setLabelText( tr( "Creating icon for file %1" ).arg( fileIt->fileName() ) ); progress.setValue( counter ); QCoreApplication::processEvents(); if ( progress.wasCanceled() ) { break; } QString filePath = fileIt->absoluteFilePath(); //test if file is svg or pixel format bool fileIsPixel = false; bool fileIsSvg = testSvgFile( filePath ); if ( !fileIsSvg ) { fileIsPixel = testImageFile( filePath ); } //exclude files that are not svg or image if ( !fileIsSvg && !fileIsPixel ) { ++counter; continue; } QListWidgetItem * listItem = new QListWidgetItem( mPreviewListWidget ); listItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled ); if ( fileIsSvg ) { QIcon icon( filePath ); listItem->setIcon( icon ); } else //for pixel formats: create icon from scaled pixmap { QPixmap iconPixmap( filePath ); if ( iconPixmap.isNull() ) { ++counter; continue; //unknown file format or other problem } //set pixmap hardcoded to 30/30, same as icon size for mPreviewListWidget QPixmap scaledPixmap( iconPixmap.scaled( QSize( 30, 30 ), Qt::KeepAspectRatio ) ); QIcon icon( scaledPixmap ); listItem->setIcon( icon ); } listItem->setText( "" ); //store the absolute icon file path as user data listItem->setData( Qt::UserRole, fileIt->absoluteFilePath() ); ++counter; } return 0; }
QWidget *QgsAttributeEditor::createAttributeEditor( QWidget *parent, QWidget *editor, QgsVectorLayer *vl, int idx, const QVariant &value, QMap<int, QWidget*> &proxyWidgets ) { if ( !vl ) return 0; QWidget *myWidget = 0; QgsVectorLayer::EditType editType = vl->editType( idx ); const QgsField &field = vl->pendingFields()[idx]; QVariant::Type myFieldType = field.type(); bool synchronized = false; switch ( editType ) { case QgsVectorLayer::UniqueValues: { QList<QVariant> values; vl->dataProvider()->uniqueValues( idx, values ); QComboBox *cb = comboBox( editor, parent ); if ( cb ) { cb->setEditable( false ); for ( QList<QVariant>::iterator it = values.begin(); it != values.end(); it++ ) cb->addItem( it->toString(), it->toString() ); myWidget = cb; } } break; case QgsVectorLayer::Enumeration: { QStringList enumValues; vl->dataProvider()->enumValues( idx, enumValues ); QComboBox *cb = comboBox( editor, parent ); if ( cb ) { QStringList::const_iterator s_it = enumValues.constBegin(); for ( ; s_it != enumValues.constEnd(); ++s_it ) { cb->addItem( *s_it, *s_it ); } myWidget = cb; } } break; case QgsVectorLayer::ValueMap: { const QMap<QString, QVariant> &map = vl->valueMap( idx ); QComboBox *cb = comboBox( editor, parent ); if ( cb ) { for ( QMap<QString, QVariant>::const_iterator it = map.begin(); it != map.end(); it++ ) { cb->addItem( it.key(), it.value() ); } myWidget = cb; } } break; case QgsVectorLayer::ValueRelation: { const QgsVectorLayer::ValueRelationData &data = vl->valueRelation( idx ); QgsVectorLayer *layer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( data.mLayer ) ); QMap< QString, QString > map; int fi = -1; if ( layer ) { int ki = layer->fieldNameIndex( data.mOrderByValue ? data.mValue : data.mKey ); int vi = layer->fieldNameIndex( data.mOrderByValue ? data.mKey : data.mValue ); if ( !data.mFilterAttributeColumn.isNull() ) fi = layer->fieldNameIndex( data.mFilterAttributeColumn ); if ( ki >= 0 && vi >= 0 ) { QgsAttributeList attributes; attributes << ki; attributes << vi; if ( fi >= 0 ) attributes << fi; layer->select( attributes, QgsRectangle(), false ); QgsFeature f; while ( layer->nextFeature( f ) ) { if ( fi >= 0 && f.attributeMap()[ fi ].toString() != data.mFilterAttributeValue ) continue; map.insert( f.attributeMap()[ ki ].toString(), f.attributeMap()[ vi ].toString() ); } } } if ( !data.mAllowMulti ) { QComboBox *cb = comboBox( editor, parent ); if ( cb ) { if ( data.mAllowNull ) { QSettings settings; cb->addItem( tr( "(no selection)" ), settings.value( "qgis/nullValue", "NULL" ).toString() ); } for ( QMap< QString, QString >::const_iterator it = map.begin(); it != map.end(); it++ ) { if ( data.mOrderByValue ) cb->addItem( it.key(), it.value() ); else cb->addItem( it.value(), it.key() ); } myWidget = cb; } } else { QListWidget *lw = listWidget( editor, parent ); if ( lw ) { QStringList checkList = value.toString().remove( QChar( '{' ) ).remove( QChar( '}' ) ).split( "," ); for ( QMap< QString, QString >::const_iterator it = map.begin(); it != map.end(); it++ ) { QListWidgetItem *item; if ( data.mOrderByValue ) { item = new QListWidgetItem( it.key() ); item->setData( Qt::UserRole, it.value() ); item->setCheckState( checkList.contains( it.value() ) ? Qt::Checked : Qt::Unchecked ); } else { item = new QListWidgetItem( it.value() ); item->setData( Qt::UserRole, it.key() ); item->setCheckState( checkList.contains( it.key() ) ? Qt::Checked : Qt::Unchecked ); } lw->addItem( item ); } myWidget = lw; } } } break; case QgsVectorLayer::Classification: { QMap<QString, QString> classes; const QgsUniqueValueRenderer *uvr = dynamic_cast<const QgsUniqueValueRenderer *>( vl->renderer() ); if ( uvr ) { const QList<QgsSymbol *> symbols = uvr->symbols(); for ( int i = 0; i < symbols.size(); i++ ) { QString label = symbols[i]->label(); QString name = symbols[i]->lowerValue(); if ( label == "" ) label = name; classes.insert( name, label ); } } const QgsCategorizedSymbolRendererV2 *csr = dynamic_cast<const QgsCategorizedSymbolRendererV2 *>( vl->rendererV2() ); if ( csr ) { const QgsCategoryList &categories = (( QgsCategorizedSymbolRendererV2 * )csr )->categories(); // FIXME: QgsCategorizedSymbolRendererV2::categories() should be const for ( int i = 0; i < categories.size(); i++ ) { QString label = categories[i].label(); QString value = categories[i].value().toString(); if ( label.isEmpty() ) label = value; classes.insert( value, label ); } } QComboBox *cb = comboBox( editor, parent ); if ( cb ) { for ( QMap<QString, QString>::const_iterator it = classes.begin(); it != classes.end(); it++ ) { cb->addItem( it.value(), it.key() ); } myWidget = cb; } } break; case QgsVectorLayer::DialRange: case QgsVectorLayer::SliderRange: case QgsVectorLayer::EditRange: { if ( myFieldType == QVariant::Int ) { int min = vl->range( idx ).mMin.toInt(); int max = vl->range( idx ).mMax.toInt(); int step = vl->range( idx ).mStep.toInt(); if ( editType == QgsVectorLayer::EditRange ) { QSpinBox *sb = 0; if ( editor ) sb = qobject_cast<QSpinBox *>( editor ); else sb = new QSpinBox( parent ); if ( sb ) { sb->setRange( min, max ); sb->setSingleStep( step ); myWidget = sb; } } else { QAbstractSlider *sl = 0; if ( editor ) { sl = qobject_cast<QAbstractSlider*>( editor ); } else if ( editType == QgsVectorLayer::DialRange ) { sl = new QDial( parent ); } else { sl = new QSlider( Qt::Horizontal, parent ); } if ( sl ) { sl->setRange( min, max ); sl->setSingleStep( step ); myWidget = sl; } } break; } else if ( myFieldType == QVariant::Double ) { QDoubleSpinBox *dsb = 0; if ( editor ) dsb = qobject_cast<QDoubleSpinBox*>( editor ); else dsb = new QDoubleSpinBox( parent ); if ( dsb ) { double min = vl->range( idx ).mMin.toDouble(); double max = vl->range( idx ).mMax.toDouble(); double step = vl->range( idx ).mStep.toDouble(); dsb->setRange( min, max ); dsb->setSingleStep( step ); myWidget = dsb; } break; } } case QgsVectorLayer::CheckBox: { QCheckBox *cb = 0; if ( editor ) cb = qobject_cast<QCheckBox*>( editor ); else cb = new QCheckBox( parent ); if ( cb ) { myWidget = cb; break; } } // fall-through case QgsVectorLayer::LineEdit: case QgsVectorLayer::TextEdit: case QgsVectorLayer::UuidGenerator: case QgsVectorLayer::UniqueValuesEditable: case QgsVectorLayer::Immutable: { QLineEdit *le = 0; QTextEdit *te = 0; QPlainTextEdit *pte = 0; QComboBox * cb = 0; if ( editor ) { le = qobject_cast<QLineEdit *>( editor ); te = qobject_cast<QTextEdit *>( editor ); pte = qobject_cast<QPlainTextEdit *>( editor ); cb = qobject_cast<QComboBox *>( editor ); } else if ( editType == QgsVectorLayer::TextEdit ) { pte = new QPlainTextEdit( parent ); } else { le = new QLineEdit( parent ); } if ( le ) { if ( editType == QgsVectorLayer::UniqueValuesEditable ) { QList<QVariant> values; vl->dataProvider()->uniqueValues( idx, values ); QStringList svalues; for ( QList<QVariant>::const_iterator it = values.begin(); it != values.end(); it++ ) svalues << it->toString(); QCompleter *c = new QCompleter( svalues ); c->setCompletionMode( QCompleter::PopupCompletion ); le->setCompleter( c ); } if ( editType == QgsVectorLayer::UuidGenerator ) { le->setReadOnly( true ); } le->setValidator( new QgsFieldValidator( le, field ) ); myWidget = le; } if ( te ) { te->setAcceptRichText( true ); myWidget = te; } if ( pte ) { myWidget = pte; } if ( cb ) { myWidget = cb; } if ( myWidget ) { myWidget->setDisabled( editType == QgsVectorLayer::Immutable ); QgsStringRelay* relay = NULL; QMap<int, QWidget*>::const_iterator it = proxyWidgets.find( idx ); if ( it != proxyWidgets.end() ) { QObject* obj = qvariant_cast<QObject*>( (*it)->property( "QgisAttrEditProxy" ) ); relay = qobject_cast<QgsStringRelay*>( obj ); } else { relay = new QgsStringRelay( myWidget ); } if ( cb && cb->isEditable() ) { synchronized = connect( relay, SIGNAL( textChanged( QString ) ), myWidget, SLOT( setEditText( QString ) ) ); synchronized &= connect( myWidget, SIGNAL( editTextChanged( QString ) ), relay, SLOT( changeText( QString ) ) ); } else { synchronized = connect( relay, SIGNAL( textChanged( QString ) ), myWidget, SLOT( setText( QString ) ) ); synchronized &= connect( myWidget, SIGNAL( textChanged( QString ) ), relay, SLOT( changeText( QString ) ) ); } if ( !cb || cb->isEditable() ) { myWidget->setProperty( "QgisAttrEditProxy", QVariant( QMetaType::QObjectStar, &relay ) ); } } } break; case QgsVectorLayer::Hidden: myWidget = 0; break; case QgsVectorLayer::FileName: case QgsVectorLayer::Calendar: { QPushButton *pb = 0; QLineEdit *le = qobject_cast<QLineEdit *>( editor ); if ( le ) { if ( le ) myWidget = le; if ( editor->parent() ) { pb = editor->parent()->findChild<QPushButton *>(); } } else { le = new QLineEdit(); pb = new QPushButton( tr( "..." ) ); QHBoxLayout *hbl = new QHBoxLayout(); hbl->addWidget( le ); hbl->addWidget( pb ); myWidget = new QWidget( parent ); myWidget->setBackgroundRole( QPalette::Window ); myWidget->setAutoFillBackground( true ); myWidget->setLayout( hbl ); } if ( pb ) { if ( editType == QgsVectorLayer::FileName ) connect( pb, SIGNAL( clicked() ), new QgsAttributeEditor( pb ), SLOT( selectFileName() ) ); if ( editType == QgsVectorLayer::Calendar ) connect( pb, SIGNAL( clicked() ), new QgsAttributeEditor( pb ), SLOT( selectDate() ) ); } } break; } QMap<int, QWidget*>::const_iterator it = proxyWidgets.find( idx ); if ( it != proxyWidgets.end() ) { if ( !synchronized ) { myWidget->setEnabled( false ); } } else { proxyWidgets.insert( idx, myWidget ); } setValue( myWidget, vl, idx, value ); return myWidget; }
PreferencesDialog::PreferencesDialog(Preferences& preferences, QWidget* parent) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint), m_preferences(preferences) { setWindowTitle(tr("Preferences")); QTabWidget* tabs = new QTabWidget(this); tabs->addTab(initGeneralTab(), tr("General")); tabs->addTab(initStatisticsTab(), tr("Statistics")); tabs->addTab(initToolbarTab(), tr("Toolbar")); tabs->addTab(initSpellingTab(), tr("Spell Checking")); tabs->setUsesScrollButtons(false); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); connect(buttons, SIGNAL(accepted()), this, SLOT(accept())); connect(buttons, SIGNAL(rejected()), this, SLOT(reject())); QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(tabs); layout->addWidget(buttons); // Load settings switch (m_preferences.goalType()) { case 1: m_option_time->setChecked(true); break; case 2: m_option_wordcount->setChecked(true); break; default: m_option_none->setChecked(true); break; } m_time->setValue(m_preferences.goalMinutes()); m_wordcount->setValue(m_preferences.goalWords()); m_show_characters->setChecked(m_preferences.showCharacters()); m_show_pages->setChecked(m_preferences.showPages()); m_show_paragraphs->setChecked(m_preferences.showParagraphs()); m_show_words->setChecked(m_preferences.showWords()); switch (m_preferences.pageType()) { case 1: m_option_paragraphs->setChecked(true); break; case 2: m_option_words->setChecked(true); break; default: m_option_characters->setChecked(true); break; } m_page_characters->setValue(m_preferences.pageCharacters()); m_page_paragraphs->setValue(m_preferences.pageParagraphs()); m_page_words->setValue(m_preferences.pageWords()); if (m_preferences.accurateWordcount()) { m_option_accurate_wordcount->setChecked(true); } else { m_option_estimate_wordcount->setChecked(true); } m_always_center->setChecked(m_preferences.alwaysCenter()); m_block_cursor->setChecked(m_preferences.blockCursor()); m_rich_text->setChecked(m_preferences.richText()); m_smooth_fonts->setChecked(m_preferences.smoothFonts()); m_smart_quotes->setChecked(m_preferences.smartQuotes()); m_double_quotes->setCurrentIndex(m_preferences.doubleQuotes()); m_single_quotes->setCurrentIndex(m_preferences.singleQuotes()); m_typewriter_sounds->setChecked(m_preferences.typewriterSounds()); m_auto_save->setChecked(m_preferences.autoSave()); m_save_positions->setChecked(m_preferences.savePositions()); int style = m_toolbar_style->findData(m_preferences.toolbarStyle()); if (style == -1) { style = m_toolbar_style->findData(Qt::ToolButtonTextUnderIcon); } m_toolbar_style->setCurrentIndex(style); QStringList actions = m_preferences.toolbarActions(); int pos = 0; foreach (const QString& action, actions) { QString text = action; bool checked = !text.startsWith("^"); if (!checked) { text.remove(0, 1); } QListWidgetItem* item = 0; if (text != "|") { int count = m_toolbar_actions->count(); for (int i = pos; i < count; ++i) { if (m_toolbar_actions->item(i)->data(Qt::UserRole).toString() == text) { item = m_toolbar_actions->takeItem(i); break; } } } else if (checked) { item = new QListWidgetItem(QString(20, QChar('-'))); item->setData(Qt::UserRole, "|"); } if (item != 0) { item->setCheckState(checked ? Qt::Checked : Qt::Unchecked); m_toolbar_actions->insertItem(pos, item); pos++; } }
BootSelectionDialog::BootSelectionDialog(const QString &defaultPartition, QWidget *parent) : QDialog(parent), _countdown(OS_SELECTION_TIMEOUT+1), ui(new Ui::BootSelectionDialog) { setWindowFlags(Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint); ui->setupUi(this); QRect s = QApplication::desktop()->screenGeometry(); if (s.height() < 500) resize(s.width()-10, s.height()-100); QDir dir; dir.mkdir("/settings"); if (QProcess::execute("mount -o remount,ro /settings") != 0 && QProcess::execute("mount -t ext4 -o ro " SETTINGS_PARTITION " /settings") != 0) { QMessageBox::critical(this, tr("Cannot display boot menu"), tr("Error mounting settings partition")); return; } /* Also mount /dev/mmcblk0p1 as it may contain icons we need */ if (QProcess::execute("mount -t vfat -o ro /dev/mmcblk0p1 /mnt") != 0) { /* Not fatal if this fails */ } QVariantList installed_os = Json::loadFromFile("/settings/installed_os.json").toList(); QSize currentsize = ui->list->iconSize(); foreach (QVariant v, installed_os) { QVariantMap m = v.toMap(); QString iconfilename = m.value("icon").toString(); QIcon icon; if (!iconfilename.isEmpty() && QFile::exists(iconfilename)) { icon = QIcon(iconfilename); QList<QSize> avs = icon.availableSizes(); if (avs.isEmpty()) { /* Icon file corrupt */ icon = QIcon(); } else { QSize iconsize = avs.first(); if (iconsize.width() > currentsize.width() || iconsize.height() > currentsize.height()) { /* Make all icons as large as the largest icon we have */ currentsize = QSize(qMax(iconsize.width(), currentsize.width()),qMax(iconsize.height(), currentsize.height())); ui->list->setIconSize(currentsize); } } } if (canBootOs(m.value("name").toString(), m)) { QListWidgetItem *item = new QListWidgetItem(icon, m.value("name").toString()+"\n"+m.value("description").toString(), ui->list); item->setData(Qt::UserRole, m); } }
ThymioFlasherDialog::ThymioFlasherDialog() { typedef std::map<int, std::pair<std::string, std::string> > PortsMap; const PortsMap ports = SerialPortEnumerator::getPorts(); QSettings settings; // Create the gui ... setWindowTitle(tr("Thymio Firmware Updater")); resize(600,500); QVBoxLayout* mainLayout = new QVBoxLayout(this); // make sure the port list is enabled only if serial ports are found unsigned sectionEnabled(ports.empty() ? 1 : 0); // serial port serialGroupBox = new QGroupBox(tr("Serial connection")); serialGroupBox->setCheckable(true); QHBoxLayout* serialLayout = new QHBoxLayout(); serial = new QListWidget(); bool serialPortSet(false); for (PortsMap::const_iterator it = ports.begin(); it != ports.end(); ++it) { const QString text(it->second.second.c_str()); QListWidgetItem* item = new QListWidgetItem(text); item->setData(Qt::UserRole, QVariant(QString::fromUtf8(it->second.first.c_str()))); serial->addItem(item); if (it->second.second.compare(0,9,"Thymio-II") == 0) { serial->setCurrentItem(item); serialPortSet = true; } } if (sectionEnabled == 0 && !serialPortSet) sectionEnabled = 1; serialGroupBox->setChecked(sectionEnabled == 0); serial->setSelectionMode(QAbstractItemView::SingleSelection); serialLayout->addWidget(serial); connect(serial, SIGNAL(itemSelectionChanged()), SLOT(setupFlashButtonState())); serialGroupBox->setLayout(serialLayout); connect(serialGroupBox, SIGNAL(clicked()), SLOT(serialGroupChecked())); mainLayout->addWidget(serialGroupBox); // custom target customGroupBox = new QGroupBox(tr("Custom connection")); customGroupBox->setCheckable(true); customGroupBox->setChecked(sectionEnabled == 1); QHBoxLayout* customLayout = new QHBoxLayout(); QLineEdit* custom = new QLineEdit(settings.value("custom target", ASEBA_DEFAULT_TARGET).toString()); customLayout->addWidget(custom); customGroupBox->setLayout(customLayout); connect(customGroupBox, SIGNAL(clicked()), SLOT(customGroupChecked())); mainLayout->addWidget(customGroupBox); // file selector QGroupBox* fileGroupBox = new QGroupBox(tr("Firmware file")); QHBoxLayout *fileLayout = new QHBoxLayout(); lineEdit = new QLineEdit(this); fileButton = new QPushButton(tr("Select..."), this); fileLayout->addWidget(fileButton); fileLayout->addWidget(lineEdit); fileGroupBox->setLayout(fileLayout); mainLayout->addWidget(fileGroupBox); // progress bar progressBar = new QProgressBar(this); progressBar->setValue(0); progressBar->setRange(0, 100); mainLayout->addWidget(progressBar); // flash and quit buttons QHBoxLayout *flashLayout = new QHBoxLayout(); flashButton = new QPushButton(tr("Update"), this); flashButton->setEnabled(false); flashLayout->addWidget(flashButton); quitButton = new QPushButton(tr("Quit"), this); flashLayout->addWidget(quitButton); mainLayout->addItem(flashLayout); // connections connect(fileButton, SIGNAL(clicked()), SLOT(openFile())); connect(flashButton, SIGNAL(clicked()), SLOT(doFlash())); connect(quitButton, SIGNAL(clicked()), SLOT(close())); connect(&flashFutureWatcher, SIGNAL(finished()), SLOT(flashFinished())); show(); }
CWPosSel::CWPosSel(QWidget *parent, mapView_t *view) : ////////////////////////////////////////////////////// QDialog(parent), ui(new Ui::CWPosSel) { ui->setupUi(this); m_earthTools.setCacheFolder(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/cache"); connect(&m_earthTools, SIGNAL(sigDone(bool,double,int)), this, SLOT(slotETDone(bool,double,int))); connect(&m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(slotLocationDone(QNetworkReply*))); SkFile f(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/data/locations/locations.dat"); if (f.open(SkFile::ReadOnly | SkFile::Text)) { QString str; QStringList l; do { str = f.readLine(); if (str.isEmpty() || str.startsWith("\n")) break; l = str.split("|"); if (l.count() != 5) { qDebug("CWPosSel read line fail!"); continue; } location_t *loc = new location_t; loc->name = l.at(0); loc->lon = l.at(1).toDouble(); loc->lat = l.at(2).toDouble(); loc->alt = l.at(3).toDouble(); loc->tz = l.at(4).toDouble(); m_tList.append(loc); QListWidgetItem *w = new QListWidgetItem(loc->name, NULL, 1); w->setData(Qt::UserRole, (qint64)loc); ui->listWidget->addItem(w); } while (1); f.close(); } ui->spinBox_8->setValue(view->geo.temp); ui->spinBox_9->setValue(view->geo.press); ui->checkBox->setChecked(!view->geo.useAtmRefraction); ui->cb_tempType->addItem("C"); ui->cb_tempType->addItem("F"); ui->cb_tempType->setCurrentIndex(view->geo.tempType); location_t loc; loc.name = view->geo.name; loc.lon = R2D(view->geo.lon); loc.lat = R2D(view->geo.lat); loc.alt = view->geo.alt; loc.tz = view->geo.tzo * 24.0; ui->doubleSpinBox_4->setValue(view->geo.sdlt * 24.0); m_view = view; setData(&loc); QShortcut *sh1 = new QShortcut(QKeySequence(Qt::Key_Delete), ui->listWidget, 0, 0, Qt::WidgetShortcut); connect(sh1, SIGNAL(activated()), this, SLOT(slotDeleteItem())); ui->widget->setModel((QSortFilterProxyModel *)ui->listWidget->model(), 0); connect(ui->widget, SIGNAL(sigSetSelection(QModelIndex&)), this, SLOT(slotSelChange(QModelIndex&))); SkFile file(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/data/locations/home.dat"); if (file.open(QFile::ReadOnly)) { QDataStream ds(&file); int count; ds >> count; for (int i = 0; i < count; i++) { location_t loc; ds >> loc.name; ds >> loc.alt; ds >> loc.lat; ds >> loc.lon; ds >> loc.tz; QVariant var; var.setValue(loc); ui->cb_home->addItem(loc.name, var); } }
ImportList::ImportList(QWidget *parent) : QDialog(parent), ui(new Ui::ImportList), selectedFile(NULL) { ui->setupUi(this); //Set up preview table ui->twPreview->setHidden(true); ui->pbRefresh->setHidden(true); connect(ui->gbPreview, SIGNAL(clicked()), this, SLOT(togglePreview())); connect(ui->pbCancel, SIGNAL(clicked()), this, SLOT(reject())); connect(ui->pbImport, SIGNAL(clicked()), this, SLOT(import())); //Browse File and Preview Related connect(ui->pbBrowse, SIGNAL(clicked()), this, SLOT(browseListFile())); connect(ui->leFilePath, SIGNAL(editingFinished()), this, SLOT(reloadSelectedFile())); connect(ui->leFilePath, SIGNAL(returnPressed()), this, SLOT(reloadSelectedFile())); connect(ui->pbRefresh, SIGNAL(clicked()), this, SLOT(reloadSelectedFile())); //Column Management Related connect(ui->pbAdd, SIGNAL(clicked()), this, SLOT(addSelectedColumns())); connect(ui->pbRemove, SIGNAL(clicked()), this, SLOT(removeSelectedColumns())); connect(ui->pbMoveUp, SIGNAL(clicked()), this, SLOT(moveSelectedUp())); connect(ui->pbMoveDown, SIGNAL(clicked()), this, SLOT(moveSelectedDown())); QListWidgetItem *item = new QListWidgetItem("Name", ui->lwAvailableColumns); item->setToolTip("Movie Title; Can contain any character"); item->setData(Qt::UserRole, QVariant::fromValue(UserRoleData(QString("\"(.*)\""), UserRoleData::Name))); ui->lwAvailableColumns->addItem(item); item = new QListWidgetItem("Year", ui->lwAvailableColumns); item->setToolTip("Year when the movie came out; format: YYYY"); item->setData(Qt::UserRole, QVariant::fromValue(UserRoleData(QString("([0-9]*)"), UserRoleData::Year))); ui->lwAvailableColumns->addItem(item); item = new QListWidgetItem("Quality", ui->lwAvailableColumns); item->setToolTip("Should be one of the following string: \"Xvid\", \"BDRIP\", \"720p\", or \"1080p\""); item->setData(Qt::UserRole, QVariant::fromValue(UserRoleData(QString("\"(.*)\""), UserRoleData::Quality))); ui->lwAvailableColumns->addItem(item); item = new QListWidgetItem("IMDB Link", ui->lwAvailableColumns); item->setToolTip("Valid link to IMDB Page."); item->setData(Qt::UserRole, QVariant::fromValue(UserRoleData(QString("\"(.*)\""), UserRoleData::IMDB))); ui->lwAvailableColumns->addItem(item); QStringList selectedColumns; m_settings.beginGroup(IMPORT_GROUP); int size = m_settings.beginReadArray(SELECTED_COLUMNS_ARRAY); for(int i = 0; i < size; i++) { m_settings.setArrayIndex(i); selectedColumns.push_front(m_settings.value(SELECTED_COLUMNS_COLUMN_KEY).toString()); } m_settings.endArray(); ui->leFilePath->setText(m_settings.value(LAST_SELECTED_FILE_KEY).toString()); reloadSelectedFile(); m_settings.endGroup(); QStringList::iterator itr = selectedColumns.begin(); for(; itr != selectedColumns.end(); ++itr) { for(int i = 0; i < ui->lwAvailableColumns->count(); i++) { if(ui->lwAvailableColumns->item(i)->text() == *itr) { ui->lwColumnOrder->insertItem(0, ui->lwAvailableColumns->takeItem(i)); break; } } } }
QWidget* ExtensionDialog::CreateWidget( extension_widget_t *p_widget ) { QLabel *label = NULL; QPushButton *button = NULL; QTextBrowser *textArea = NULL; QLineEdit *textInput = NULL; QCheckBox *checkBox = NULL; QComboBox *comboBox = NULL; QListWidget *list = NULL; SpinningIcon *spinIcon = NULL; struct /*extension_widget_t::*/extension_widget_value_t *p_value = NULL; // sunqueen modify assert( p_widget->p_sys_intf == NULL ); switch( p_widget->type ) { case EXTENSION_WIDGET_LABEL: label = new QLabel( qfu( p_widget->psz_text ), this ); p_widget->p_sys_intf = label; label->setTextFormat( Qt::RichText ); label->setOpenExternalLinks( true ); return label; case EXTENSION_WIDGET_BUTTON: button = new QPushButton( qfu( p_widget->psz_text ), this ); clickMapper->setMapping( button, new WidgetMapper( p_widget ) ); CONNECT( button, clicked(), clickMapper, map() ); p_widget->p_sys_intf = button; return button; case EXTENSION_WIDGET_IMAGE: label = new QLabel( this ); label->setPixmap( QPixmap( qfu( p_widget->psz_text ) ) ); if( p_widget->i_width > 0 ) label->setMaximumWidth( p_widget->i_width ); if( p_widget->i_height > 0 ) label->setMaximumHeight( p_widget->i_height ); label->setScaledContents( true ); p_widget->p_sys_intf = label; return label; case EXTENSION_WIDGET_HTML: textArea = new QTextBrowser( this ); textArea->setOpenExternalLinks( true ); textArea->setHtml( qfu( p_widget->psz_text ) ); p_widget->p_sys_intf = textArea; return textArea; case EXTENSION_WIDGET_TEXT_FIELD: textInput = new QLineEdit( this ); textInput->setText( qfu( p_widget->psz_text ) ); textInput->setReadOnly( false ); textInput->setEchoMode( QLineEdit::Normal ); inputMapper->setMapping( textInput, new WidgetMapper( p_widget ) ); /// @note: maybe it would be wiser to use textEdited here? CONNECT( textInput, textChanged(const QString &), inputMapper, map() ); p_widget->p_sys_intf = textInput; return textInput; case EXTENSION_WIDGET_PASSWORD: textInput = new QLineEdit( this ); textInput->setText( qfu( p_widget->psz_text ) ); textInput->setReadOnly( false ); textInput->setEchoMode( QLineEdit::Password ); inputMapper->setMapping( textInput, new WidgetMapper( p_widget ) ); /// @note: maybe it would be wiser to use textEdited here? CONNECT( textInput, textChanged(const QString &), inputMapper, map() ); p_widget->p_sys_intf = textInput; return textInput; case EXTENSION_WIDGET_CHECK_BOX: checkBox = new QCheckBox( this ); checkBox->setText( qfu( p_widget->psz_text ) ); checkBox->setChecked( p_widget->b_checked ); clickMapper->setMapping( checkBox, new WidgetMapper( p_widget ) ); CONNECT( checkBox, stateChanged( int ), clickMapper, map() ); p_widget->p_sys_intf = checkBox; return checkBox; case EXTENSION_WIDGET_DROPDOWN: comboBox = new QComboBox( this ); comboBox->setEditable( false ); for( p_value = p_widget->p_values; p_value != NULL; p_value = p_value->p_next ) { comboBox->addItem( qfu( p_value->psz_text ), p_value->i_id ); } /* Set current item */ if( p_widget->psz_text ) { int idx = comboBox->findText( qfu( p_widget->psz_text ) ); if( idx >= 0 ) comboBox->setCurrentIndex( idx ); } selectMapper->setMapping( comboBox, new WidgetMapper( p_widget ) ); CONNECT( comboBox, currentIndexChanged( const QString& ), selectMapper, map() ); return comboBox; case EXTENSION_WIDGET_LIST: list = new QListWidget( this ); list->setSelectionMode( QAbstractItemView::ExtendedSelection ); for( p_value = p_widget->p_values; p_value != NULL; p_value = p_value->p_next ) { QListWidgetItem *item = new QListWidgetItem( qfu( p_value->psz_text ) ); item->setData( Qt::UserRole, p_value->i_id ); list->addItem( item ); } selectMapper->setMapping( list, new WidgetMapper( p_widget ) ); CONNECT( list, itemSelectionChanged(), selectMapper, map() ); return list; case EXTENSION_WIDGET_SPIN_ICON: spinIcon = new SpinningIcon( this ); spinIcon->play( p_widget->i_spin_loops ); p_widget->p_sys_intf = spinIcon; return spinIcon; default: msg_Err( p_intf, "Widget type %d unknown", p_widget->type ); return NULL; } }
TextPalette::TextPalette(QWidget* parent) : QWidget(parent) { setWindowFlags(Qt::Tool); setupUi(this); pCommon = new Palette; pCommon->setMag(0.8); pCommon->setGrid(33, 60); pCommon->setReadOnly(true); pSmufl = new Palette; pSmufl->setMag(0.8); pSmufl->setGrid(33, 60); pSmufl->setReadOnly(true); pUnicode = new Palette; pUnicode->setMag(0.8); pUnicode->setGrid(33, 60); pUnicode->setReadOnly(true); PaletteScrollArea* psa = new PaletteScrollArea(pCommon); psa->setRestrictHeight(false); tabWidget->clear(); tabWidget->addTab(psa, tr("Common Symbols")); psa = new PaletteScrollArea(pSmufl); psa->setRestrictHeight(false); QSplitter* ws = new QSplitter; lws = new QListWidget; lws->addItems(smuflRanges()->keys()); lws->setCurrentRow(0); ws->addWidget(lws); ws->addWidget(psa); tabWidget->addTab(ws, tr("Musical Symbols")); psa = new PaletteScrollArea(pUnicode); psa->setRestrictHeight(false); QSplitter* wu = new QSplitter; lwu = new QListWidget; lwu->setSortingEnabled(true); for (int i = 0; i < unicodeRangeNames.length(); i++) { QListWidgetItem* newItem = new QListWidgetItem(qApp->translate("accidental", unicodeRangeNames.at(i).toUtf8().constData())); newItem->setData(Qt::UserRole, i); lwu->addItem(newItem); if (i == 0) lwu->setCurrentItem(newItem); } wu->addWidget(lwu); wu->addWidget(psa); tabWidget->addTab(wu, tr("Unicode Symbols")); connect(lws, SIGNAL(currentRowChanged(int)), SLOT(populateSmufl())); connect(lwu, SIGNAL(currentRowChanged(int)), SLOT(populateUnicode())); // others are done in setFont populateSmufl(); setFocusPolicy(Qt::NoFocus); }
/*! \internal Should be connected to all \l QNetworkReply::finished signals in order to process possible HTTP-redirects correctly. */ void SettingsDialog::downloadCompleted() { QScopedPointer<QNetworkReply, QScopedPointerDeleteLater> reply( qobject_cast<QNetworkReply *>(sender())); m_replies.removeOne(reply.data()); if (reply->error() != QNetworkReply::NoError) { if (reply->error() != QNetworkReply::OperationCanceledError) { const int ret = QMessageBox::warning(this, tr("Network Error"), reply->errorString(), QMessageBox::Ok | QMessageBox::Retry); if (ret == QMessageBox::Retry) { QNetworkReply *newReply = download(reply->request().url()); // Copy properties newReply->setProperty(DocsetNameProperty, reply->property(DocsetNameProperty)); newReply->setProperty(DownloadTypeProperty, reply->property(DownloadTypeProperty)); newReply->setProperty(ListItemIndexProperty, reply->property(ListItemIndexProperty)); connect(newReply, &QNetworkReply::finished, this, &SettingsDialog::downloadCompleted); return; } bool ok; QListWidgetItem *listItem = ui->availableDocsetList->item( reply->property(ListItemIndexProperty).toInt(&ok)); if (ok && listItem) listItem->setData(ProgressItemDelegate::ShowProgressRole, false); } if (m_replies.isEmpty()) resetProgress(); return; } QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (redirectUrl.isValid()) { if (redirectUrl.isRelative()) redirectUrl = reply->request().url().resolved(redirectUrl); /// TODO: Verify if scheme can be missing if (redirectUrl.scheme().isEmpty()) redirectUrl.setScheme(reply->request().url().scheme()); QNetworkReply *newReply = download(redirectUrl); // Copy properties newReply->setProperty(DocsetNameProperty, reply->property(DocsetNameProperty)); newReply->setProperty(DownloadTypeProperty, reply->property(DownloadTypeProperty)); newReply->setProperty(ListItemIndexProperty, reply->property(ListItemIndexProperty)); connect(newReply, &QNetworkReply::finished, this, &SettingsDialog::downloadCompleted); return; } switch (reply->property(DownloadTypeProperty).toUInt()) { case DownloadDocsetList: { const QByteArray data = reply->readAll(); const QDir cacheDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)); QScopedPointer<QFile> file(new QFile(cacheDir.filePath(DocsetListCacheFileName))); if (file->open(QIODevice::WriteOnly)) file->write(data); ui->lastUpdatedLabel->setText(QFileInfo(file->fileName()) .lastModified().toString(Qt::SystemLocaleShortDate)); QJsonParseError jsonError; const QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError); if (jsonError.error != QJsonParseError::NoError) { QMessageBox::warning(this, tr("Error"), tr("Corrupted docset list: ") + jsonError.errorString()); break; } processDocsetList(jsonDoc.array()); resetProgress(); break; } case DownloadDashFeed: { DocsetMetadata metadata = DocsetMetadata::fromDashFeed(reply->request().url(), reply->readAll()); if (metadata.urls().isEmpty()) { QMessageBox::critical(this, QStringLiteral("Zeal"), tr("Invalid docset feed!")); break; } m_userFeeds[metadata.name()] = metadata; QNetworkReply *reply = download(metadata.url()); reply->setProperty(DocsetNameProperty, metadata.name()); reply->setProperty(DownloadTypeProperty, DownloadDocset); connect(reply, &QNetworkReply::finished, this, &SettingsDialog::downloadCompleted); break; } case DownloadDocset: { const QString docsetName = reply->property(DocsetNameProperty).toString(); const DocsetMetadata metadata = m_availableDocsets.contains(docsetName) ? m_availableDocsets[docsetName] : m_userFeeds[docsetName]; /// TODO: Implement an explicit and verbose docset update logic QDir dir(m_application->settings()->docsetPath); const QString docsetDirName = docsetName + QLatin1String(".docset"); if (dir.exists(docsetDirName)) { m_docsetRegistry->remove(docsetName); const QString tmpName = QStringLiteral(".toDelete") + QString::number(QDateTime::currentMSecsSinceEpoch()); dir.rename(docsetDirName, tmpName); QtConcurrent::run([=] { QDir d(dir); if (!d.cd(tmpName)) return; d.removeRecursively(); }); } QTemporaryFile *tmpFile = m_tmpFiles[docsetName]; if (!tmpFile) { tmpFile = new QTemporaryFile(this); tmpFile->open(); m_tmpFiles.insert(docsetName, tmpFile); } while (reply->bytesAvailable()) tmpFile->write(reply->read(1024 * 1024)); // Use small chunks tmpFile->close(); QListWidgetItem *item = findDocsetListItem(metadata.title()); if (item) { item->setData(ProgressItemDelegate::ValueRole, 0); item->setData(ProgressItemDelegate::FormatRole, tr("Installing: %p%")); } m_tmpFiles.insert(metadata.name(), tmpFile); m_application->extract(tmpFile->fileName(), m_application->settings()->docsetPath, metadata.name() + QLatin1String(".docset")); break; } } // If all enqueued downloads have finished executing if (m_replies.isEmpty()) resetProgress(); }
AdvanceButtonDialog::AdvanceButtonDialog(JoyButton *button, QWidget *parent) : QDialog(parent, Qt::Dialog), ui(new Ui::AdvanceButtonDialog) { ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose); this->button = button; oldRow = 0; if (this->button->getToggleState()) { ui->toggleCheckbox->setChecked(true); } if (this->button->isUsingTurbo()) { ui->turboCheckbox->setChecked(true); ui->turboSlider->setEnabled(true); } int interval = this->button->getTurboInterval() / 10; if (interval < MINIMUMTURBO) { interval = JoyButton::ENABLEDTURBODEFAULT / 10; } ui->turboSlider->setValue(interval); this->changeTurboText(interval); QListIterator<JoyButtonSlot*> iter(*(this->button->getAssignedSlots())); while (iter.hasNext()) { JoyButtonSlot *buttonslot = iter.next(); SimpleKeyGrabberButton *existingCode = new SimpleKeyGrabberButton(this); existingCode->setText(buttonslot->getSlotString()); existingCode->setValue(buttonslot->getSlotCode(), buttonslot->getSlotCodeAlias(), buttonslot->getSlotMode()); QListWidgetItem *item = new QListWidgetItem(); item->setData(Qt::UserRole, QVariant::fromValue<SimpleKeyGrabberButton*>(existingCode)); QHBoxLayout *layout= new QHBoxLayout(); layout->setContentsMargins(10, 0, 10, 0); layout->addWidget(existingCode); QWidget *widget = new QWidget(); widget->setLayout(layout); item->setSizeHint(widget->sizeHint()); ui->slotListWidget->addItem(item); ui->slotListWidget->setItemWidget(item, widget); connectButtonEvents(existingCode); } appendBlankKeyGrabber(); populateSetSelectionComboBox(); if (this->button->getSetSelection() > -1 && this->button->getChangeSetCondition() != JoyButton::SetChangeDisabled) { int selectIndex = (int)this->button->getChangeSetCondition(); selectIndex += this->button->getSetSelection() * 3; if (this->button->getOriginSet() < this->button->getSetSelection()) { selectIndex -= 3; } ui->setSelectionComboBox->setCurrentIndex(selectIndex); } fillTimeComboBoxes(); ui->actionTenthsComboBox->setCurrentIndex(1); updateActionTimeLabel(); changeTurboForSequences(); if (button->isCycleResetActive()) { ui->autoResetCycleCheckBox->setEnabled(true); ui->autoResetCycleCheckBox->setChecked(true); checkCycleResetWidgetStatus(true); } if (button->getCycleResetTime() != 0) { populateAutoResetInterval(); } updateWindowTitleButtonName(); connect(ui->turboCheckbox, SIGNAL(clicked(bool)), ui->turboSlider, SLOT(setEnabled(bool))); connect(ui->turboSlider, SIGNAL(valueChanged(int)), this, SLOT(checkTurboIntervalValue(int))); connect(ui->insertSlotButton, SIGNAL(clicked()), this, SLOT(insertSlot())); connect(ui->deleteSlotButton, SIGNAL(clicked()), this, SLOT(deleteSlot())); connect(ui->clearAllPushButton, SIGNAL(clicked()), this, SLOT(clearAllSlots())); connect(ui->pausePushButton, SIGNAL(clicked()), this, SLOT(insertPauseSlot())); connect(ui->holdPushButton, SIGNAL(clicked()), this, SLOT(insertHoldSlot())); connect(ui->cyclePushButton, SIGNAL(clicked()), this, SLOT(insertCycleSlot())); connect(ui->distancePushButton, SIGNAL(clicked()), this, SLOT(insertDistanceSlot())); connect(ui->releasePushButton, SIGNAL(clicked()), this, SLOT(insertReleaseSlot())); connect(ui->actionHundredthsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateActionTimeLabel())); connect(ui->actionSecondsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateActionTimeLabel())); connect(ui->actionMinutesComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateActionTimeLabel())); connect(ui->actionTenthsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateActionTimeLabel())); connect(ui->toggleCheckbox, SIGNAL(clicked(bool)), button, SLOT(setToggle(bool))); connect(ui->turboCheckbox, SIGNAL(clicked(bool)), this, SLOT(checkTurboSetting(bool))); connect(ui->setSelectionComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateSetSelection())); connect(ui->mouseModPushButton, SIGNAL(clicked()), this, SLOT(insertMouseSpeedModSlot())); connect(ui->slotListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(performStatsWidgetRefresh(QListWidgetItem*))); connect(ui->actionHundredthsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkSlotTimeUpdate())); connect(ui->actionTenthsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkSlotTimeUpdate())); connect(ui->actionSecondsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkSlotTimeUpdate())); connect(ui->actionMinutesComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkSlotTimeUpdate())); connect(ui->distanceSpinBox, SIGNAL(valueChanged(int)), this, SLOT(checkSlotDistanceUpdate())); connect(ui->mouseSpeedModSpinBox, SIGNAL(valueChanged(int)), this, SLOT(checkSlotMouseModUpdate())); connect(ui->pressTimePushButton, SIGNAL(clicked()), this, SLOT(insertKeyPressSlot())); connect(ui->delayPushButton, SIGNAL(clicked()), this, SLOT(insertDelaySlot())); connect(ui->autoResetCycleCheckBox, SIGNAL(clicked(bool)), this, SLOT(checkCycleResetWidgetStatus(bool))); connect(ui->autoResetCycleCheckBox, SIGNAL(clicked(bool)), this, SLOT(setButtonCycleReset(bool))); connect(ui->resetCycleDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setButtonCycleResetInterval(double))); connect(button, SIGNAL(toggleChanged(bool)), ui->toggleCheckbox, SLOT(setChecked(bool))); connect(button, SIGNAL(turboChanged(bool)), this, SLOT(checkTurboSetting(bool))); }
void AboutDialog::addLicense(const QString &name, Licenses license) { QListWidgetItem *item = new QListWidgetItem(name); item->setData(Qt::UserRole, license); ui->creditsList->addItem(item); }
void AppearanceWidget::addColorItem(const QString &text, const QColor &color) { QListWidgetItem *listItem = new QListWidgetItem(text, ui.codeViewColorsList); listItem->setData(Qt::UserRole, color); ui.codeViewColorsList->addItem(listItem); }
PerformanceCounterSelection::PerformanceCounterSelection(ICaptureContext &ctx, const QList<GPUCounter> &selectedCounters, QWidget *parent) : QDialog(parent), ui(new Ui::PerformanceCounterSelection), m_Ctx(ctx) { ui->setupUi(this); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->counterTree->setColumns({QString()}); ui->counterTree->setHeaderHidden(true); connect(ui->counterTree, &RDTreeWidget::currentItemChanged, [this](RDTreeWidgetItem *item, RDTreeWidgetItem *) -> void { const QVariant d = item->data(0, CounterDescriptionRole); if(d.isValid()) { ui->counterDescription->setText( QString(lit("<b>%1</b><hr>%2")).arg(item->text(0)).arg(d.toString())); } }); connect(ui->save, &QPushButton::pressed, this, &PerformanceCounterSelection::Save); connect(ui->load, &QPushButton::pressed, this, &PerformanceCounterSelection::Load); connect(ui->sampleCounters, &QPushButton::pressed, this, &PerformanceCounterSelection::accept); connect(ui->cancel, &QPushButton::pressed, this, &PerformanceCounterSelection::reject); connect(ui->counterTree, &RDTreeWidget::itemChanged, [this](RDTreeWidgetItem *item, int) -> void { const QVariant d = item->data(0, CounterIdRole); static bool recurse = false; if(d.isValid()) { if(item->checkState(0) == Qt::Checked) { // Add QListWidgetItem *listItem = new QListWidgetItem(ui->enabledCounters); listItem->setText(item->text(0)); listItem->setData(CounterIdRole, d); m_SelectedCounters.insert((GPUCounter)d.toUInt(), listItem); } else { // Remove QListWidgetItem *listItem = m_SelectedCounters.take((GPUCounter)d.toUInt()); delete listItem; } if(!recurse) { recurse = true; updateParentCheckState(item->parent()); recurse = false; } } else if(!recurse) { Qt::CheckState prev = item->data(0, PreviousCheckStateRole).value<Qt::CheckState>(); if(item->checkState(0) != prev) { recurse = true; if(item->checkState(0) == Qt::Checked) { checkAllChildren(item); } else { uncheckAllChildren(item); } item->setData(0, PreviousCheckStateRole, item->checkState(0)); updateParentCheckState(item); recurse = false; } } }); ui->counterTree->setMouseTracking(true); ctx.Replay().AsyncInvoke([this, selectedCounters](IReplayController *controller) -> void { QVector<CounterDescription> counterDescriptions; for(const GPUCounter counter : controller->EnumerateCounters()) { counterDescriptions.append(controller->DescribeCounter(counter)); } GUIInvoke::call([counterDescriptions, selectedCounters, this]() -> void { SetCounters(counterDescriptions); SetSelectedCounters(selectedCounters); }); }); ui->counterTree->setContextMenuPolicy(Qt::CustomContextMenu); QObject::connect(ui->counterTree, &RDTreeWidget::customContextMenuRequested, this, &PerformanceCounterSelection::counterTree_contextMenu); }
TrashDialog::TrashDialog(QJSValue notes, MainWindow *mainWindow, QWidget *parent) : MasterDialog(parent), ui(new Ui::TrashDialog) { this->mainWindow = mainWindow; ui->setupUi(this); setupMainSplitter(); QPushButton *button; ui->buttonBox->clear(); button = new QPushButton(tr("&Restore selected note on server")); button->setToolTip(tr("<h3>Slower, but with note versions</h3>" "<p>The note will be restored on your ownCloud " "server with all versions.</p>" "<p>You will have to wait until it is synced to " "QOwnNotes by ownCloud sync.</p>")); button->setProperty("ActionRole", RestoreOnServer); button->setDefault(false); button->setIcon( QIcon::fromTheme( "view-restore", QIcon(":/icons/breeze-qownnotes/16x16/view-restore.svg"))); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); button = new QPushButton(tr("&Download selected note")); button->setToolTip(tr("<h3>Faster, but without versions</h3>" "<p>The note will be created with the text from the preview.</p>" "<p>The note versions on your ownCloud server will not be restored " "and the note will remain in the trash.</p>" "<p>You can always restore the note and its versions later.</p>")); button->setProperty("ActionRole", Download); button->setDefault(false); button->setIcon( QIcon::fromTheme( "edit-download", QIcon(":/icons/breeze-qownnotes/16x16/edit-download.svg"))); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); button = new QPushButton(tr("&Cancel")); button->setProperty("ActionRole", Cancel); button->setIcon( QIcon::fromTheme( "dialog-cancel", QIcon(":/icons/breeze-qownnotes/16x16/dialog-cancel.svg"))); button->setDefault(true); ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole); connect(this->ui->buttonBox, SIGNAL(clicked(QAbstractButton *)), SLOT(dialogButtonClicked(QAbstractButton *))); connect(this, SIGNAL(finished(int)), this, SLOT(storeSettings())); QString itemName; QString dateString; QString data; int timestamp; ui->trashListWidget->clear(); dataList = new QStringList(); timestampList = new QList<int>; // init the iterator for the versions QJSValueIterator notesIterator(notes); // iterate over the trashed notes while (notesIterator.hasNext()) { notesIterator.next(); QJSValue property = notesIterator.value().property("noteName"); if (property.isUndefined()) { continue; } itemName = property.toString(); if (itemName == "") { continue; } dateString = notesIterator.value().property("dateString").toString(); data = notesIterator.value().property("data").toString(); timestamp = notesIterator.value().property("timestamp").toInt(); QString fileName = notesIterator.value().property("fileName").toString(); QListWidgetItem *item = new QListWidgetItem(); item->setText(itemName); item->setData(Qt::UserRole, fileName); item->setToolTip(dateString); ui->trashListWidget->addItem(item); dataList->append(data); timestampList->append(timestamp); } ui->trashListWidget->setCurrentRow(0); ui->noteBrowser->setText(dataList->at(0)); }
void LaunchyWidget::showAlternatives(bool show, bool resetSelection) { dropTimer->stop(); // If main launchy window is not visible, do nothing if (!isVisible()) return; if (show) { if (searchResults.size() < 1) return; int mode = gSettings->value("GenOps/condensedView", 0).toInt(); int i = 0; for (; i < searchResults.size(); ++i) { qDebug() << "Alternative" << i << ":" << searchResults[i].fullPath; QString fullPath = QDir::toNativeSeparators(searchResults[i].fullPath); QListWidgetItem* item; if (i < alternatives->count()) { item = alternatives->item(i); } else { item = new QListWidgetItem(fullPath, alternatives); } if (item->data(mode == 1 ? ROLE_SHORT : ROLE_FULL) != fullPath) { // condensedTempIcon is a blank icon or null item->setData(ROLE_ICON, *condensedTempIcon); } item->setData(mode == 1 ? ROLE_FULL : ROLE_SHORT, searchResults[i].shortName); item->setData(mode == 1 ? ROLE_SHORT : ROLE_FULL, fullPath); if (i >= alternatives->count()) alternatives->addItem(item); } while (alternatives->count() > i) { delete alternatives->takeItem(i); } if (resetSelection) { alternatives->setCurrentRow(0); } iconExtractor.processIcons(searchResults); int numViewable = gSettings->value("GenOps/numviewable", "4").toInt(); int min = alternatives->count() < numViewable ? alternatives->count() : numViewable; // The stylesheet doesn't load immediately, so we cache the rect here if (alternativesRect.isNull()) alternativesRect = alternatives->geometry(); QRect rect = alternativesRect; rect.setHeight(min * alternatives->sizeHintForRow(0)); rect.translate(pos()); // Is there room for the dropdown box? if (rect.y() + rect.height() > qApp->desktop()->height()) { // Only move it if there's more space above // In both cases, ensure it doesn't spill off the screen if (pos().y() + input->pos().y() > qApp->desktop()->height() / 2) { rect.moveTop(pos().y() + input->pos().y() - rect.height()); if (rect.top() < 0) rect.setTop(0); } else { rect.setBottom(qApp->desktop()->height()); } } alternatives->setGeometry(rect); alternatives->show(); alternatives->setFocus(); qApp->syncX(); } else { // clear the selection before hiding to prevent flicker alternatives->setCurrentRow(-1); alternatives->repaint(); alternatives->hide(); iconExtractor.stop(); } }
void MainWindow::openArchive() { QString buffer; QuestionItem * q_item; QStringList qa_flaglist; bool qa_flaglist_found; QStringList qa_anslist; bool qa_anslist_found; QStringList qa_correctanslist; bool qa_correctanslist_found; QStringList qa_diflist; bool qa_diflist_found; QStringList qa_selectiontypelist; bool qa_selectiontypelist_found; ArchivedSession * archived_session; bool rearchive; QSettings archive(QSettings::IniFormat, QSettings::UserScope, "Michal Tomlein", "iTest"); QStringList dbs = archive.value("databases").toStringList(); if (!dbs.contains(current_db_name)) { return; } QStringList sns = archive.value(QString("%1/sessions").arg(current_db_name)).toStringList(); for (int i = 0; i < sns.count(); ++i) { buffer = archive.value(QString("%1/%2").arg(current_db_name).arg(sns.at(i))).toString(); if (buffer.isEmpty()) { continue; } archived_session = new ArchivedSession(this, buffer); current_db_archivedsessions.insert(archived_session->dateTime(), archived_session); QListWidgetItem * item = new QListWidgetItem(QString("%1 - %2").arg(archived_session->dateTimeToString()).arg(archived_session->name())); SVLASListWidget->insertItem(0, item); item->setData(Qt::UserRole, archived_session->dateTime()); rearchive = false; buffer = archive.value(QString("%1/%2/PassMark").arg(current_db_name).arg(sns.at(i))).toString(); if (!buffer.isEmpty()) { archived_session->loadPassMark(buffer); } else { rearchive = true; } buffer = archive.value(QString("%1/%2/StudentsPassed").arg(current_db_name).arg(sns.at(i))).toString(); if (buffer.length() == archived_session->numStudents()) { for (int i = 0; i < archived_session->numStudents(); ++i) { archived_session->student(i)->setPassed(buffer.at(i) == '+'); } } else { for (int i = 0; i < archived_session->numStudents(); ++i) { archived_session->student(i)->setPassed(archived_session->passMark().check(archived_session->student(i)->results(), ¤t_db_questions, archived_session->scoringSystem())); } rearchive = true; } int numres = 0; for (int s = 0; s < archived_session->numStudents(); ++s) { numres += archived_session->student(s)->results()->count(); } qa_flaglist = archive.value(QString("%1/%2/QAFlags").arg(current_db_name).arg(sns.at(i))).toString().split(";"); qa_flaglist_found = qa_flaglist.count() == numres; qa_anslist = archive.value(QString("%1/%2/QAAnswers").arg(current_db_name).arg(sns.at(i))).toString().split(";"); qa_anslist_found = qa_anslist.count() == numres; qa_correctanslist = archive.value(QString("%1/%2/QACorrectAnswers").arg(current_db_name).arg(sns.at(i))).toString().split(";"); qa_correctanslist_found = qa_correctanslist.count() == numres; qa_diflist = archive.value(QString("%1/%2/QADifs").arg(current_db_name).arg(sns.at(i))).toString().split(";"); qa_diflist_found = qa_diflist.count() == numres; qa_selectiontypelist = archive.value(QString("%1/%2/QASeletionTypes").arg(current_db_name).arg(sns.at(i))).toString().split(";"); qa_selectiontypelist_found = qa_selectiontypelist.count() == numres; if (!qa_flaglist_found || !qa_anslist_found || !qa_correctanslist_found || !qa_diflist_found || !qa_selectiontypelist_found) { rearchive = true; } int x = 0; for (int s = 0; s < archived_session->numStudents(); ++s) { QMapIterator<QString, QuestionAnswer> qa(*(archived_session->student(s)->results())); QuestionAnswer qans; while (qa.hasNext()) { qa.next(); q_item = NULL; qans = qa.value(); if (qa_flaglist_found) { qans.setFlag(qa_flaglist.at(x).toInt()); } if (qa_anslist_found) { qans.setAnswered((Question::Answer)qa_anslist.at(x).toInt()); } if (qa_correctanslist_found) { qans.setCorrectAnswer((Question::Answer)qa_correctanslist.at(x).toInt()); } if (qa_diflist_found) { qans.setDifficulty(qa_diflist.at(x).toInt()); } if (qa_selectiontypelist_found) { qans.setSelectionType((Question::SelectionType)qa_selectiontypelist.at(x).toInt()); } if (!qa_flaglist_found || !qa_correctanslist_found || !qa_diflist_found || !qa_selectiontypelist_found) { QMapIterator<QListWidgetItem *, QuestionItem *> q(current_db_questions); while (q.hasNext()) { q.next(); if (q.value()->name() == qa.key()) { q_item = q.value(); break; } } if (q_item == NULL) { if (!qa_flaglist_found) { qans.setFlag(-1); } } else { if (!qa_flaglist_found) { qans.setFlag(q_item->flag()); } if (!qa_correctanslist_found) { qans.setCorrectAnswer(q_item->correctAnswer()); } if (!qa_diflist_found) { qans.setDifficulty(q_item->difficulty()); } if (!qa_selectiontypelist_found) { qans.setSelectionType(q_item->selectionType()); } } } archived_session->student(s)->results()->insert(qa.key(), qans); x++; } } buffer = archive.value(QString("%1/%2/ScoringSystem").arg(current_db_name).arg(sns.at(i))).toString(); if (!buffer.isEmpty()) { ScoringSystem sys(buffer); archived_session->setScoringSystem(sys); } else { archived_session->setScoringSystem(ScoringSystem()); rearchive = true; } if (rearchive) { archived_session->archive(); } } hideArchive(); }
void TriangulationSidebar::addLandmark(QPointF line) { QString str = "Landmark "+QString::number(landmarksListWidget->count()+1); QListWidgetItem *item = new QListWidgetItem(str); item->setData(Qt::UserRole, line); landmarksListWidget->addItem(item); }
QDialog *PhotoPlugin::configDialog() { if ( !m_configDialog ) { // Initializing configuration dialog m_configDialog = new QDialog(); ui_configWidget = new Ui::PhotoConfigWidget; ui_configWidget->setupUi( m_configDialog ); // add licenses to the list widget QListWidgetItem *ccByNcSa2 = new QListWidgetItem( ui_configWidget->m_licenseListWidget ); ccByNcSa2->setText( tr("Attribution-NonCommercial-ShareAlike License") ); ccByNcSa2->setIcon( QIcon() ); ccByNcSa2->setCheckState( Qt::Checked ); ccByNcSa2->setData( Qt::UserRole+1, 1 ); ccByNcSa2->setData( Qt::UserRole+2, "http://creativecommons.org/licenses/by-nc-sa/2.0/" ); ui_configWidget->m_licenseListWidget->addItem( ccByNcSa2 ); QListWidgetItem *ccByNc2 = new QListWidgetItem( ui_configWidget->m_licenseListWidget ); ccByNc2->setText( tr("Attribution-NonCommercial License") ); ccByNc2->setIcon( QIcon() ); ccByNc2->setCheckState( Qt::Checked ); ccByNc2->setData( Qt::UserRole+1, 2 ); ccByNc2->setData( Qt::UserRole+2, "http://creativecommons.org/licenses/by-nc/2.0/" ); ui_configWidget->m_licenseListWidget->addItem( ccByNc2 ); QListWidgetItem *ccByNcNd2 = new QListWidgetItem( ui_configWidget->m_licenseListWidget ); ccByNcNd2->setText( tr("Attribution-NonCommercial-NoDerivs License") ); ccByNcNd2->setIcon( QIcon() ); ccByNcNd2->setCheckState( Qt::Checked ); ccByNcNd2->setData( Qt::UserRole+1, 3 ); ccByNcNd2->setData( Qt::UserRole+2, "http://creativecommons.org/licenses/by-nc-nd/2.0/" ); ui_configWidget->m_licenseListWidget->addItem( ccByNcNd2 ); QListWidgetItem *ccBy2 = new QListWidgetItem( ui_configWidget->m_licenseListWidget ); ccBy2->setText( tr("Attribution License") ); ccBy2->setIcon( QIcon() ); ccBy2->setCheckState( Qt::Checked ); ccBy2->setData( Qt::UserRole+1, 4 ); ccBy2->setData( Qt::UserRole+2, "http://creativecommons.org/licenses/by/2.0/" ); ui_configWidget->m_licenseListWidget->addItem( ccBy2 ); QListWidgetItem *ccBySa2 = new QListWidgetItem( ui_configWidget->m_licenseListWidget ); ccBySa2->setText( tr("Attribution-ShareAlike License") ); ccBySa2->setIcon( QIcon() ); ccBySa2->setCheckState( Qt::Checked ); ccBySa2->setData( Qt::UserRole+1, 5 ); ccBySa2->setData( Qt::UserRole+2, "http://creativecommons.org/licenses/by-sa/2.0/" ); ui_configWidget->m_licenseListWidget->addItem( ccBySa2 ); QListWidgetItem *ccByNd2 = new QListWidgetItem( ui_configWidget->m_licenseListWidget ); ccByNd2->setText( tr("Attribution-NoDerivs License") ); ccByNd2->setIcon( QIcon() ); ccByNd2->setCheckState( Qt::Checked ); ccByNd2->setData( Qt::UserRole+1, 6 ); ccByNd2->setData( Qt::UserRole+2, "http://creativecommons.org/licenses/by-nd/2.0/" ); ui_configWidget->m_licenseListWidget->addItem( ccByNd2 ); QListWidgetItem *noLicense = new QListWidgetItem( ui_configWidget->m_licenseListWidget ); noLicense->setText( tr("No known copyright restrictions") ); noLicense->setIcon( QIcon() ); noLicense->setCheckState( Qt::Checked ); noLicense->setData( Qt::UserRole+1, 7 ); noLicense->setData( Qt::UserRole+2, "http://flickr.com/commons/usage/" ); ui_configWidget->m_licenseListWidget->addItem( noLicense ); readSettings(); ui_configWidget->m_itemNumberSpinBox->setRange( 0, maximumNumberOfItems ); connect( ui_configWidget->m_buttonBox, SIGNAL(accepted()), SLOT(writeSettings()) ); connect( ui_configWidget->m_buttonBox, SIGNAL(rejected()), SLOT(readSettings()) ); QPushButton *applyButton = ui_configWidget->m_buttonBox->button( QDialogButtonBox::Apply ); connect( applyButton, SIGNAL(clicked()), this, SLOT(writeSettings()) ); } return m_configDialog; }
void ThemesInstallWindow::downloadDone(bool error) { qDebug() << "[Themes] Download done, error:" << error; disconnect(logger, SIGNAL(aborted()), getter, SLOT(abort())); disconnect(logger, SIGNAL(aborted()), this, SLOT(close())); themesInfo.open(); QSettings iniDetails(themesInfo.fileName(), QSettings::IniFormat, this); QStringList tl = iniDetails.childGroups(); qDebug() << "[Themes] Theme site result:" << iniDetails.value("error/code").toString() << iniDetails.value("error/description").toString() << iniDetails.value("error/query").toString(); if(error) { logger->addItem(tr("Network error: %1.\n" "Please check your network and proxy settings.") .arg(getter->errorString()), LOGERROR); getter->abort(); logger->setFinished(); disconnect(getter, SIGNAL(done(bool)), this, SLOT(downloadDone(bool))); connect(logger, SIGNAL(closed()), this, SLOT(close())); return; } // handle possible error codes if(iniDetails.value("error/code").toInt() != 0 || !iniDetails.contains("error/code")) { qDebug() << "[Themes] Theme site returned an error:" << iniDetails.value("error/code"); logger->addItem(tr("the following error occured:\n%1") .arg(iniDetails.value("error/description", "unknown error").toString()), LOGERROR); logger->setFinished(); connect(logger, SIGNAL(closed()), this, SLOT(close())); return; } logger->addItem(tr("done."), LOGOK); logger->setFinished(); logger->close(); // setup list for(int i = 0; i < tl.size(); i++) { iniDetails.beginGroup(tl.at(i)); // skip all themes without name field set (i.e. error section) if(iniDetails.value("name").toString().isEmpty()) { iniDetails.endGroup(); continue; } qDebug() << "[Themes] adding to list:" << tl.at(i); // convert to unicode and replace HTML-specific entities QByteArray raw = iniDetails.value("name").toByteArray(); QTextCodec* codec = QTextCodec::codecForHtml(raw); QString name = codec->toUnicode(raw); name.replace(""", "\"").replace("&", "&"); name.replace("<", "<").replace(">", ">"); QListWidgetItem *w = new QListWidgetItem; w->setData(Qt::DisplayRole, name.trimmed()); w->setData(Qt::UserRole, tl.at(i)); ui.listThemes->addItem(w); iniDetails.endGroup(); } // check if there's a themes "MOTD" available if(iniDetails.contains("status/msg")) { // check if there's a localized msg available QString lang = RbSettings::value(RbSettings::Language).toString().split("_").at(0); QString msg; if(iniDetails.contains("status/msg." + lang)) msg = iniDetails.value("status/msg." + lang).toString(); else msg = iniDetails.value("status/msg").toString(); qDebug() << "[Themes] MOTD" << msg; if(!msg.isEmpty()) QMessageBox::information(this, tr("Information"), msg); } }
void UI_Annotationswindow::updateList(void) { char str[MAX_ANNOTATION_LEN + 32], *str_tmp; int i, len, sequence_nr=0, jump=0, modified=0; QListWidgetItem *listitem; QString string; QByteArray ba; selected = -1; #ifdef Q_OS_WIN32 QFont specialfont("courier", 11, QFont::Normal, true); #else QFont specialfont("andale mono", 12, QFont::Normal, true); #endif specialfont.setPixelSize(12); list->clear(); edfplus_annotation_sort(&mainwindow->annotationlist[file_num]); annotation = mainwindow->annotationlist[file_num]; while(annotation != NULL) { if(annotation->hided_in_list) { annotation = annotation->next_annotation; sequence_nr++; continue; } string = QString::fromUtf8(annotation->annotation); ba = string.toUtf8(); str_tmp = ba.data(); len = 0; for(i=0; ; i++) { if(str_tmp[i]==0) break; if(((((unsigned char *)str_tmp)[i])&224)==192) len++; } for(i=0; i<len; i++) string.append(' '); if(relative) { if((annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) < 0LL) { snprintf(str, (MAX_ANNOTATION_LEN + 32) / 2, " -%2i:%02i:%02i.%04i", (int)((-(annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION)/ 3600), (int)(((-(annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION) % 3600) / 60), (int)((-(annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION) % 60), (int)((-(annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) % TIME_DIMENSION) / 1000LL)); } else { snprintf(str, (MAX_ANNOTATION_LEN + 32) / 2, " %3i:%02i:%02i.%04i", (int)(((annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION)/ 3600), (int)((((annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION) % 3600) / 60), (int)(((annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION) % 60), (int)(((annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) % TIME_DIMENSION) / 1000LL)); } } else { snprintf(str, MAX_ANNOTATION_LEN + 32, " %3i:%02i:%02i.%04i", (int)((((annotation->onset + mainwindow->edfheaderlist[file_num]->l_starttime) / TIME_DIMENSION)/ 3600) % 24), (int)((((annotation->onset + mainwindow->edfheaderlist[file_num]->l_starttime) / TIME_DIMENSION) % 3600) / 60), (int)(((annotation->onset + mainwindow->edfheaderlist[file_num]->l_starttime) / TIME_DIMENSION) % 60), (int)(((annotation->onset + mainwindow->edfheaderlist[file_num]->l_starttime) % TIME_DIMENSION) / 1000LL)); } str[MAX_ANNOTATION_LEN + 31] = 0; remove_trailing_zeros(str); if(string.size() < 20) { string = string.leftJustified(20, ' '); } string.append(QString::fromLatin1(str)); listitem = new QListWidgetItem(string, list); listitem->setData(Qt::UserRole, QVariant(sequence_nr)); if(annotation->modified==1) { listitem->setFont(specialfont); listitem->setForeground(Qt::red); modified = 1; } if((annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) < 0LL) { snprintf(str, (MAX_ANNOTATION_LEN + 32) / 2, "onset: -%i:%02i:%02i.%04i", (int)((-(annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION)/ 3600), (int)(((-(annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION) % 3600) / 60), (int)((-(annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION) % 60), (int)((-(annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) % TIME_DIMENSION) / 1000LL)); } else { snprintf(str, (MAX_ANNOTATION_LEN + 32) / 2, "onset: %2i:%02i:%02i.%04i", (int)(((annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION)/ 3600), (int)((((annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION) % 3600) / 60), (int)(((annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) / TIME_DIMENSION) % 60), (int)(((annotation->onset - mainwindow->edfheaderlist[file_num]->starttime_offset) % TIME_DIMENSION) / 1000LL)); } if(annotation->duration[0]!=0) { snprintf(str + strlen(str), (MAX_ANNOTATION_LEN + 32) / 2, "\nduration: %s",annotation->duration); } str[MAX_ANNOTATION_LEN + 31] = 0; remove_trailing_zeros(str); strcat(str, "\n\n"); string = QString::fromLatin1(str); string.append(QString::fromUtf8(annotation->annotation)); listitem->setToolTip(string); if(annotation->selected) { selected = sequence_nr; annotation->selected = 0; if(annotation->jump) { jump = 1; annotation->jump = 0; } } annotation = annotation->next_annotation; sequence_nr++; } if(mainwindow->annot_editor_active) { if(selected>=0) { list->setCurrentRow(selected, QItemSelectionModel::ClearAndSelect); mainwindow->annotationEditDock->set_selected_annotation(file_num, selected); if(jump) { jump = 0; annotation_selected(list->currentItem()); } selected = -1; } if(modified) { mainwindow->annotations_edited = 1; mainwindow->save_act->setEnabled(true); } } }
RoleAssignDialog::RoleAssignDialog(QWidget *parent) : QDialog(parent) { setWindowTitle(tr("Assign roles and seats")); list = new QListWidget; list->setFlow(QListView::TopToBottom); list->setMovement(QListView::Static); QStringList role_list = Sanguosha->getRoleList(ServerInfo.GameMode); if (Config.FreeAssignSelf) { QString text = QString("%1[%2]") .arg(Self->screenName()) .arg(Sanguosha->translate("lord")); QListWidgetItem *item = new QListWidgetItem(text, list); item->setData(Qt::UserRole, Self->objectName()); role_mapping.insert(Self->objectName(), "lord"); } else { QList<const ClientPlayer *> players = ClientInstance->getPlayers(); for (int i = 0; i < players.length(); i++) { QString role = role_list.at(i); const ClientPlayer *player = players.at(i); QString text = QString("%1[%2]") .arg(player->screenName()) .arg(Sanguosha->translate(role)); QListWidgetItem *item = new QListWidgetItem(text, list); item->setData(Qt::UserRole, player->objectName()); role_mapping.insert(player->objectName(), role); } } QVBoxLayout *vlayout = new QVBoxLayout; role_ComboBox = new QComboBox; role_ComboBox->addItem(tr("Lord"), "lord"); role_ComboBox->addItem(tr("Loyalist"), "loyalist"); role_ComboBox->addItem(tr("Renegade"), "renegade"); role_ComboBox->addItem(tr("Rebel"), "rebel"); QPushButton *moveUpButton = new QPushButton(tr("Move up")); QPushButton *moveDownButton = new QPushButton(tr("Move down")); QPushButton *okButton = new QPushButton(tr("OK")); QPushButton *cancelButton = new QPushButton(tr("Cancel")); if (Config.FreeAssignSelf) { moveUpButton->setEnabled(false); moveDownButton->setEnabled(false); } vlayout->addWidget(role_ComboBox); vlayout->addWidget(moveUpButton); vlayout->addWidget(moveDownButton); vlayout->addStretch(); vlayout->addWidget(okButton); vlayout->addWidget(cancelButton); QHBoxLayout *layout = new QHBoxLayout(); layout->addWidget(list); layout->addLayout(vlayout); QVBoxLayout *mainlayout = new QVBoxLayout(); mainlayout->addLayout(layout); setLayout(mainlayout); connect(role_ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateRole(int))); connect(list, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(updateRole(QListWidgetItem *))); connect(moveUpButton, SIGNAL(clicked()), this, SLOT(moveUp())); connect(moveDownButton, SIGNAL(clicked()), this, SLOT(moveDown())); connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); }
void EventsWidget::populaListaProcedures() { GameData *gameData = GameData::getInstance(); ui->listWidgetProcedures->clear(); std::vector<ProcedureData*> *procedureList = NULL; if(!ui->comboBoxTarget->itemData(ui->comboBoxTarget->currentIndex(), Qt::UserRole).isNull()) { GameObject *gameObject = (GameObject*) ui->comboBoxTarget->itemData(ui->comboBoxTarget->currentIndex(), Qt::UserRole).value<void*>(); if(gameObject == NULL) { QListWidgetItem *itemProcedureAlways = new QListWidgetItem(QString(gameData->procedureGlobalAlways->name.c_str())); itemProcedureAlways->setData(Qt::UserRole, QVariant::fromValue((void*) gameData->procedureGlobalAlways)); QListWidgetItem *itemProcedureStart = new QListWidgetItem(QString(gameData->procedureGlobalStart->name.c_str())); itemProcedureStart->setData(Qt::UserRole, QVariant::fromValue((void*) gameData->procedureGlobalStart)); QListWidgetItem *itemProcedureEnd = new QListWidgetItem(QString(gameData->procedureGlobalEnd->name.c_str())); itemProcedureEnd->setData(Qt::UserRole, QVariant::fromValue((void*) gameData->procedureGlobalEnd)); ui->listWidgetProcedures->addItem(itemProcedureAlways); ui->listWidgetProcedures->addItem(itemProcedureStart); ui->listWidgetProcedures->addItem(itemProcedureEnd); procedureList = gameData->procedureList; } else { QListWidgetItem *itemProcedureAlways = new QListWidgetItem(QString(gameObject->procedureGlobalAlways->name.c_str())); itemProcedureAlways->setData(Qt::UserRole, QVariant::fromValue((void*) gameObject->procedureGlobalAlways)); QListWidgetItem *itemProcedureStart = new QListWidgetItem(QString(gameObject->procedureGlobalStart->name.c_str())); itemProcedureStart->setData(Qt::UserRole, QVariant::fromValue((void*) gameObject->procedureGlobalStart)); QListWidgetItem *itemProcedureEnd = new QListWidgetItem(QString(gameObject->procedureGlobalEnd->name.c_str())); itemProcedureEnd->setData(Qt::UserRole, QVariant::fromValue((void*) gameObject->procedureGlobalEnd)); ui->listWidgetProcedures->addItem(itemProcedureAlways); ui->listWidgetProcedures->addItem(itemProcedureStart); ui->listWidgetProcedures->addItem(itemProcedureEnd); procedureList = gameObject->procedureList; } } if(procedureList != NULL) { for(std::vector<ProcedureData*>::iterator it = procedureList->begin(); it != procedureList->end(); ++it) { ProcedureData* procedureData = *it; QListWidgetItem *procedureItem = new QListWidgetItem(QString(procedureData->name.c_str())); procedureItem->setData(Qt::UserRole, QVariant::fromValue((void*) procedureData)); ui->listWidgetProcedures->addItem(procedureItem); } } ui->listWidgetProcedures->setCurrentRow(0); }