コード例 #1
0
ファイル: kitoptionspage.cpp プロジェクト: 55171514/qtcreator
void KitOptionsPageWidget::cloneKit()
{
    Kit *current = currentKit();
    if (!current)
        return;

    Kit *k = m_model->markForAddition(current);
    QModelIndex newIdx = m_model->indexOf(k);
    m_kitsView->scrollTo(newIdx);
    m_selectionModel->select(newIdx,
                             QItemSelectionModel::Clear
                             | QItemSelectionModel::SelectCurrent
                             | QItemSelectionModel::Rows);
}
コード例 #2
0
ファイル: routeview.cpp プロジェクト: allenck/mapper
void RouteView::StartRoute_S()         //SLOT
{
    //SQL sql;
    mainWindow * myParent = qobject_cast<mainWindow*>(m_parent);
    QItemSelectionModel * model = ui->selectionModel();
    QModelIndexList indexes = model->selectedIndexes();
    //qint32 row = model->currentIndex().row();
    //qint32 col =model->currentIndex().column();
    QModelIndex Index = indexes.at(0);
    qint32 segmentId = Index.data().toInt();

    TerminalInfo ti = SQL::instance()->getTerminalInfo(route, name, endDate);
    SQL::instance()->updateTerminals(route, name, startDate, endDate, segmentId, "S",  ti.route < 0 ? segmentId : ti.endSegment, ti.route < 0 ? "?" : ti.endWhichEnd);
    ti = SQL::instance()->getTerminalInfo(route, name, endDate);
    startSegment = segmentId;
    updateRouteView();
//    Object[] objArray = new Object[] { ti.startLatLng.lat, ti.startLatLng.lon, myParent->getRouteMarkerImagePath(myParent->m_alphaRoute, true) };
//    webBrowser1.Document.InvokeScript("addRouteStartMarker", objArray);
    QVariantList objArray;
    objArray << ti.startLatLng.lat()<< ti.startLatLng.lon()<<myParent->getRouteMarkerImagePath(alphaRoute, false);
    webViewBridge::instance()->processScript("addRouteStartMarker", objArray);

}
コード例 #3
0
void FolderManager::runCommand(const QString &name)
{
  qDebug() << "FolderManager::runCommand()" << name;

  FolderView *sourceView = currentFolderView(m_active_side);
  FolderView *targetView = currentFolderView((m_active_side == LeftSide) ? RightSide : LeftSide);

  if (! sourceView) {
    qDebug() << "no source view";
    return;
  }

  if (name == "parent") {
    QDir dir(sourceView->fileSystemModel()->rootPath());
    dir.cdUp();
    sourceView->navigateToPath(dir.absolutePath());
  }
  else if (name == "select-all") {
    sourceView->selectAll();
  }
  else if (name == "select-none") {
    sourceView->clearSelection();
  }
  else if (name == "invert-selection") {
    QItemSelectionModel *selectionModel  = sourceView->selectionModel();
    selectionModel->select(selectionModel->selection(), QItemSelectionModel::Toggle);

#if 0
    QAbstractItemModel  *model        = sourceView->model();
    QModelIndex          topLeft      = model->index(0, 0);
    QModelIndex          bottomRight  = model->index(model->rowCount(parent)-1,
                                                     model->columnCount(parent)-1);
    QItemSelection selection(topLeft, bottomRight);
    selectionModel->select(selection, QItemSelectionModel::Toggle);
#endif
  }
}
コード例 #4
0
ファイル: FilesModel.cpp プロジェクト: wangd/mp3diags
void FilesModel::matchSelToNotes()
{
    QItemSelectionModel* pNotesSelModel (m_pCommonData->m_pNotesG->selectionModel());
    QModelIndexList notesLstSel (pNotesSelModel->selection().indexes());

    set<int> sSel;
    for (QModelIndexList::iterator it = notesLstSel.begin(), end = notesLstSel.end(); it != end; ++it)
    {
//cout << "cell sel at " << it->row() << "x" << it->column() << endl;
        const Note* pNote (m_pCommonData->getCrtNotes()[it->row()]);
        int nPos (m_pCommonData->findPos(pNote));
        sSel.insert(nPos);
    }

    m_pCommonData->m_pFilesG->selectionModel()->clearSelection();

    for (set<int>::const_iterator it = sSel.begin(), end = sSel.end(); it != end; ++it)
    {
        m_pCommonData->m_pFilesG->selectionModel()->select(index(m_pCommonData->getFilesGCrtRow(), *it + 1), QItemSelectionModel::Select);
//cout << "selecting " << m_pCommonData->getFilesGCrtRow() << "x" << *it + 1 << endl;
    }

    m_pCommonData->m_pFilesG->selectionModel()->select(index(m_pCommonData->getFilesGCrtRow(), 0), QItemSelectionModel::Select);
}
コード例 #5
0
ファイル: FilesModel.cpp プロジェクト: wangd/mp3diags
// makes current and selects the specified row and emits a change signal regardless of the element that was selected before; makes current the default invalid index (-1,-1) if the table is empty;
void FilesModel::selectRow(int nRow, const vector<int>& vnSel /* = std::vector<int>()*/)
{
    QItemSelectionModel* pSelModel (m_pCommonData->m_pFilesG->selectionModel());
//m_pCommonData->printFilesCrt();

    {
        NonblockingGuard g (m_pCommonData->m_bChangeGuard);
        if (!g) { return; }
        pSelModel->clear(); // 2008.07.08: this doesn't work quite as expected: it does trigger SelectionChanged, but it changes the current item after emitting the signal, so whoever catches it, doesn't know what the current item is (it's probably in the second param of CurrentChanged, but that doesn't help SelectionChanged, which has QItemSelection params, which don't seem to offer any way to get at the "current" index)
    }

//m_pCommonData->printFilesCrt();

    emit layoutChanged();

    m_nPrevCurrentRow = -2; // to make sure that onFilesGSelChanged() updates the notes and streams regardless of whether there are any files in m_pFilesG or not
    if (!m_pCommonData->getViewHandlers().empty())
    {
        //pSelModel->select(index(0, 0), QItemSelectionModel::Current);
        //pSelModel->select(index(0, 0), QItemSelectionModel::Select);

        //m_pCommonData->printFilesCrt();
        m_pCommonData->m_pFilesG->setCurrentIndex(index(nRow, 0)); // this sometimes calls onFilesGSelChanged(), but not always;
        //m_pCommonData->printFilesCrt();
    }

    if (-2 == m_nPrevCurrentRow)
    {
        onFilesGSelChanged();
    }

    for (int i = 0, n = cSize(vnSel); i < n; ++i)
    {
        pSelModel->select(pSelModel->model()->index(vnSel[i], 0), QItemSelectionModel::Select);
    }
}
コード例 #6
0
void CreateDataPlumeDialog::on_acceptProposalsButton_clicked()
{
    if(ui->proposalsTableWidget->selectedItems().count() == 0)
    {
        QMessageBox msg;
        msg.setText("Please select one or more proposals to accept.");
        msg.exec();
        return;
    }

    // get the proposal id's
    std::vector<uint256> proposalIds;
    QItemSelectionModel* selectionModel = ui->proposalsTableWidget->selectionModel();
    QModelIndexList selected = selectionModel->selectedRows();
    for(int i= 0; i< selected.count();i++)
    {
        QModelIndex index = selected.at(i);
        int r = index.row();
        uint256 hash = uint256(ui->proposalsTableWidget->item(r, 4)->text().toStdString());
        proposalIds.push_back(hash);
    }

    bool hasErrors = false;
    CPlumeApi api;
    BOOST_FOREACH(uint256 p, proposalIds)
    {
        std::string err;
        bool res = api.AcceptProposal(p, err);
        if(!res)
        {
            hasErrors = true;
            QMessageBox msg;
            msg.setText(QString::fromStdString(err));
            msg.exec();
        }
    }
コード例 #7
0
ファイル: MantidMatrix.cpp プロジェクト: nimgould/mantid
/** Called when switching between tabs
*  @param index :: The index of the new active tab
*/
void MantidMatrix::viewChanged(int index)
{
  // get the previous view and selection model
  QTableView* prevView=(QTableView*)m_tabs->widget(m_PrevIndex);
  if(prevView)
  {
    QItemSelectionModel *oldSelModel = prevView->selectionModel();
    QItemSelectionModel *selModel = activeView()->selectionModel();
    // Copy the selection from the previous tab into the newly-activated one
    selModel->select(oldSelModel->selection(),QItemSelectionModel::Select);
    // Clear the selection on the now-hidden tab
    oldSelModel->clearSelection();

    m_PrevIndex=index;
    //get the previous tab scrollbar positions
    int hValue=  prevView->horizontalScrollBar()->value();
    int vValue = prevView->verticalScrollBar()->value();
    //to synchronize the views
    //set  the previous view  scrollbar positions to current view
    activeView()->horizontalScrollBar()->setValue(hValue);
    activeView()->verticalScrollBar()->setValue(vValue);
  }

}
コード例 #8
0
ファイル: localview.cpp プロジェクト: caidongyun/nullfxp
void LocalView::slot_refresh_directory_tree()
{
    //qDebug() <<__FUNCTION__<<": "<<__LINE__<<":"<< __FILE__;

    QItemSelectionModel *ism = this->uiw->treeView->selectionModel();
    QModelIndex cidx, idx;

    if (ism != 0) {
        if (ism->hasSelection()) {
            cidx = ism->currentIndex();
            idx = ism->model()->index(cidx.row(), 0, cidx.parent());
            // QModelIndex origIndex = this->dir_file_model->mapToSource(mil.at(0));
            QModelIndex origIndex = this->dir_file_model->mapToSource(idx);
        }
        // QModelIndexList mil = ism->selectedIndexes();
        // if (mil.count() > 0) {
        //     // model->refresh(mil.at(0));
        //     QModelIndex origIndex = this->dir_file_model->mapToSource(mil.at(0));
        //     q_debug()<<mil.at(0)<<origIndex;
        //     // model->refresh(origIndex);
        // }
    }
    this->dir_file_model->refresh(this->uiw->tableView->rootIndex());
}
コード例 #9
0
void WineProcessWidget::procKillSelected_Click(void){
    if (QMessageBox::warning(this, tr("Warning"), tr("This action will send a KILL(-9) signal to selected processes<br><br>It is HIGH risk to damage wine normal state.<br><br>Do you really want to proceed?"), QMessageBox::Yes, QMessageBox::No)==QMessageBox::No)
        return;

    QItemSelectionModel *selectionModel = procTable->selectionModel();

    QModelIndexList indexes = selectionModel->selectedIndexes();
    QModelIndex index;
    QList<int> procList;

    foreach(index, indexes) {
        if (index.column()==0)
            procList.append(model->index(index.row(), 0, QModelIndex()).data().toInt());
    }

    if (procList.count()<=0)
        return;

    for (int i=0; i<procList.count(); i++){
        QString cmd = QString("kill -9 %1").arg(procList.at(i));

        if (system(cmd.toAscii().data())==-1){
            QMessageBox::warning(this, tr("Error"), tr("Can't run: %1").arg(cmd.toAscii().data()), QMessageBox::Ok);
#ifdef DEBUG
            qDebug()<<"[EE] Fail to run: "<<cmd;
#endif
        } else {
            emit(changeStatusText(tr("It seems process %1 killed successfully.").arg(procList.at(i))));
#ifdef DEBUG
            qDebug()<<"[ii] Run OK: "<<cmd;
#endif
        }
    }

    return;
}
コード例 #10
0
ファイル: QxFileBrowser.cpp プロジェクト: corelon/paco
void QxFileBrowser::contextMenuEvent(QContextMenuEvent* event)
{
	QRect cwdViewRect(dirView_->viewport()->mapToGlobal(QPoint(0, 0)), dirView_->viewport()->size());
	QRect recentViewRect(recentView_->viewport()->mapToGlobal(QPoint(0, 0)), recentView_->viewport()->size());
	QRect bookmarksViewRect(bookmarksView_->viewport()->mapToGlobal(QPoint(0, 0)), bookmarksView_->viewport()->size());
	QPoint pos = event->globalPos();
	
	if (cwdViewRect.contains(pos)) {
		QItemSelectionModel* sm = dirView_->selectionModel();
		bool multiSelect = (sm->selectedRows().count() > 1);
		renameAction_->setDisabled(multiSelect);
		bookmarkAction_->setEnabled(cwdModel_->isDir(dirView_->currentIndex()));
		dirView_->ignoreNextFocusOutEvent();
		contextMenu_->exec(pos);
	}
	else if (recentView_->isVisible() && (recentViewRect.contains(pos))) {
		dirView_->ignoreNextFocusOutEvent();
		recentContextMenu_->exec(pos);
	}
	else if (bookmarksView_->isVisible() && (bookmarksViewRect.contains(pos))) {
		dirView_->ignoreNextFocusOutEvent();
		bookmarksContextMenu_->exec(pos);
	}
}
コード例 #11
0
void BookmarkDialog::addNewFolder()
{
    QItemSelectionModel *model = ui.treeView->selectionModel();
    const QModelIndexList &list = model->selection().indexes();

    QModelIndex index;
    if (!list.isEmpty())
        index = list.at(0);

    QModelIndex newFolder =
        bookmarkManager->addNewFolder(proxyModel->mapToSource(index));
    if (newFolder.isValid()) {
        ui.treeView->expand(index);
        const QModelIndex &index = proxyModel->mapFromSource(newFolder);
        model->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);

        ui.bookmarkFolders->clear();
        ui.bookmarkFolders->addItems(bookmarkManager->bookmarkFolders());

        const QString &name = index.data().toString();
        ui.bookmarkFolders->setCurrentIndex(ui.bookmarkFolders->findText(name));
    }
    ui.treeView->setFocus();
}
コード例 #12
0
void QgsSvgSelectorWidget::setSvgPath( const QString& svgPath )
{
  QString updatedPath( "" );

  // skip possible urls, excepting those that may locally resolve
  if ( !svgPath.contains( "://" ) || ( svgPath.contains( "file://", Qt::CaseInsensitive ) ) )
  {
    QString resolvedPath = QgsSymbolLayerV2Utils::symbolNameToPath( svgPath.trimmed() );
    if ( !resolvedPath.isNull() )
    {
      updatedPath = resolvedPath;
    }
  }

  mCurrentSvgPath = updatedPath;

  mFileLineEdit->blockSignals( true );
  mFileLineEdit->setText( updatedPath );
  mFileLineEdit->blockSignals( false );

  mImagesListView->selectionModel()->blockSignals( true );
  QAbstractItemModel* m = mImagesListView->model();
  QItemSelectionModel* selModel = mImagesListView->selectionModel();
  for ( int i = 0; i < m->rowCount(); i++ )
  {
    QModelIndex idx( m->index( i, 0 ) );
    if ( m->data( idx ).toString() == svgPath )
    {
      selModel->select( idx, QItemSelectionModel::SelectCurrent );
      selModel->setCurrentIndex( idx, QItemSelectionModel::SelectCurrent );
      mImagesListView->scrollTo( idx );
      break;
    }
  }
  mImagesListView->selectionModel()->blockSignals( false );
}
コード例 #13
0
void window_addtacheunaire::ajouter_prerequis(Tache * newTache)
{
    //gestion prérequis
    if (ui->cb_prereq->isChecked()&&newTache!=NULL)
    {
        QItemSelectionModel *selection = ui->list_prereq->selectionModel();
        QModelIndexList listeSelections = selection->selectedIndexes();

        for (int i = 0 ; i < listeSelections.size() ; i++)
        {
            QVariant elementSelectionne = modele->data(listeSelections[i], Qt::DisplayRole);
            QString titreTache = elementSelectionne.toString();

            std::list<Tache*> taches = Model::getTaches();
            std::list<Tache*>::iterator it = taches.begin();
            for (unsigned int i = 0 ; i < taches.size() ; i++)
            {
                QString titre = (*it)->getTitre();
                if (titre == titreTache)
                {
                    try
                    {
                        newTache->ajouterPrerequis((*it));
                    }
                    catch (CalendarException& e)
                    {
                        QMessageBox::critical(this, "Erreur", e.getInfo());
                        return;

                    }
                }
                it++;
            }
        }
    }
}
コード例 #14
0
void MatrixValuesDialog::setMatrix(Matrix* m)
{
    if (!m)
        return;

	matrix = m;
	commands->setText(m->formula());

    endCol->setValue(m->numCols());
    endRow->setValue(m->numRows());

    if (m->viewType() == Matrix::TableView){
        QItemSelectionModel *selModel = m->selectionModel();
        if (selModel->hasSelection()){
            QItemSelectionRange selection = selModel->selection().first();
            if (selection.width() > 1 || selection.height() > 1){
                startCol->setValue(selection.left()+1);
                startRow->setValue(selection.top()+1);
                endCol->setValue(selection.right()+1);
                endRow->setValue(selection.bottom()+1);
            }
        }
    }
}
コード例 #15
0
void EntrySelectionModel::selectedEntriesChanged() {
  // when clearSelection() is called on the other models, then there's a cascading series of calls to
  // selectedEntriesChanged(). But we only care about the first one
  if(m_processing) {
    return;
  }
  m_processing = true;
  // we need to grab all the selected indexes in the caller
  QItemSelectionModel* selectionModel = qobject_cast<QItemSelectionModel*>(sender());
  Q_ASSERT(selectionModel);
  if(!selectionModel) {
    return;
  }

  QSet<Data::EntryPtr> entries;
  foreach(const QModelIndex& index, selectionModel->selectedIndexes()) {
    Data::EntryPtr entry = index.data(EntryPtrRole).value<Data::EntryPtr>();
    if(entry) {
      entries += entry;
    }
  }
  if(!entries.isEmpty()) {
    m_selectedEntries = entries.toList();
    emit entriesSelected(m_selectedEntries);
    // for every selection model which did not call this function. clear the selection
    foreach(const QWeakPointer<QItemSelectionModel>& ptr, m_modelList) { //krazy:exclude=foreach
      QItemSelectionModel* const otherModel = ptr.data();
      if(otherModel && otherModel != selectionModel) {
        otherModel->clearSelection();
      } else if(!otherModel) {
        // since the filter or loan view could be created multiple times
        // the selection model might be added multiple times
        // since foreach() creates a copy of the list, it's ok to remove this here
        m_modelList.removeOne(ptr);
      }
    }
コード例 #16
0
bool TableView::setSelectedRows(QList<int> rows)
{
	QItemSelectionModel * selection = selectionModel();
	selection->clear();

	TableModel * currentModel = static_cast<TableModel *>(model());

	QItemSelection totalSelection;
	for(int i = 0; i < rows.size(); i++)
	{
		if(!currentModel->isValidRow(rows[i]))
		{
			continue;
		}

		QModelIndex index = model()->index(rows[i], 0);
		QItemSelection currentSelection(index, index);
		totalSelection.merge(currentSelection, QItemSelectionModel::SelectCurrent);
	}
	selection->select(totalSelection, QItemSelectionModel::ClearAndSelect);
	setSelectionModel(selection);

	return true;
}
コード例 #17
0
ファイル: addressoverviewwindow.cpp プロジェクト: butjar/C4J
void AddressOverviewWindow::editEntry()
{
    QTableView *temp = static_cast<QTableView*>(ui->AddressesTableView);
    QSortFilterProxyModel *proxy = static_cast<QSortFilterProxyModel*>(temp->model());
    QItemSelectionModel *selectionModel = temp->selectionModel();
    QModelIndexList indexes = selectionModel->selectedRows();
    QModelIndex index, i;
    QString firstName;
    QString lastName;
    QString address;
    QString city;
    QString zipCode;
    int row = -1;

    foreach (index, indexes) {
        row = proxy->mapToSource(index).row();
        i = model->index(row, 0, QModelIndex());
        QVariant varFirstName = model->data(i, Qt::DisplayRole);
        firstName = varFirstName.toString();

        i = model->index(row, 1, QModelIndex());
        QVariant varLastName = model->data(i, Qt::DisplayRole);
        lastName = varLastName.toString();

        i = model->index(row, 2, QModelIndex());
        QVariant varAddr = model->data(i, Qt::DisplayRole);
        address = varAddr.toString();

        i = model->index(row, 3, QModelIndex());
        QVariant varCity = model->data(i, Qt::DisplayRole);
        city = varCity.toString();

        i = model->index(row, 4, QModelIndex());
        QVariant varZip = model->data(i, Qt::DisplayRole);
        zipCode = varZip.toString();
    }
コード例 #18
0
ファイル: localview.cpp プロジェクト: caidongyun/nullfxp
void LocalView::slot_copy_path_url()
{
    QItemSelectionModel *ism = this->curr_item_view->selectionModel();
    QModelIndex cidx, idx;

    if (ism == 0) {
        qDebug()<<"Why???? no QItemSelectionModel??";        
        return;
    }
    
    // QModelIndexList mil = ism->selectedIndexes();
    if (!ism->hasSelection()) {
        qDebug()<<" why???? no QItemSelectionModel??";
        return;
    }

    cidx = ism->currentIndex();
    idx = ism->model()->index(cidx.row(), 0, cidx.parent());

    QString local_file = this->curr_item_view==this->uiw->treeView
        ? this->dir_file_model->filePath(idx) : this->model->filePath(idx);
    
    QApplication::clipboard()->setText(local_file);
}
コード例 #19
0
void FolderNavigationWidget::setCurrentFile(const QString &filePath)
{
    // Try to find directory of current file
    bool pathOpened = false;
    if (!filePath.isEmpty())  {
        const QFileInfo fi(filePath);
        if (fi.exists())
            pathOpened = setCurrentDirectory(fi.absolutePath());
    }
    if (!pathOpened)  // Default to home.
        setCurrentDirectory(Utils::PathChooser::homePath());

    // Select the current file.
    if (pathOpened) {
        const QModelIndex fileIndex = m_fileSystemModel->index(filePath);
        if (fileIndex.isValid()) {
            QItemSelectionModel *selections = m_listView->selectionModel();
            const QModelIndex mainIndex = m_filterModel->mapFromSource(fileIndex);
            selections->setCurrentIndex(mainIndex, QItemSelectionModel::SelectCurrent
                                                 | QItemSelectionModel::Clear);
            m_listView->scrollTo(mainIndex);
        }
    }
}
コード例 #20
0
void TreeComboBox::showPopup()
{
    QComboBox::showPopup();
    // now clean up things we want different
    QItemSelectionModel *sm = view()->selectionModel();
    sm->clearSelection();
    view()->setSelectionMode( m_selectionmode );
    view()->setSelectionBehavior( QAbstractItemView::SelectRows );
    foreach ( const QModelIndex &i, m_currentIndexes ) {
        if ( i.isValid() ) {
            sm->select( i, QItemSelectionModel::Select | QItemSelectionModel::Rows );
        }
    }
    if ( ! sm->selectedRows().contains( sm->currentIndex() ) ) {
        sm->setCurrentIndex( sm->selectedRows().value( 0 ), QItemSelectionModel::NoUpdate );
    }
}
コード例 #21
0
ファイル: ccDBRoot.cpp プロジェクト: markgenemei/trunk
void ccDBRoot::selectEntity(ccHObject* obj)
{
    bool ctrlPushed = (QApplication::keyboardModifiers () & Qt::ControlModifier);

    QItemSelectionModel* selectionModel = m_dbTreeWidget->selectionModel();
	assert(selectionModel);

	//valid object? then we will try to select (or toggle) it
	if (obj)
	{
		QModelIndex selectedIndex = index(obj);
		if (selectedIndex.isValid())
		{
			//if CTRL is pushed
			if (ctrlPushed)
			{
				//default case: toggle current item selection state
				if (!obj->isSelected())
				{
					QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
					if (!selectedIndexes.empty())
					{
						//special case: labels can only be merged with labels!
						if (obj->isA(CC_2D_LABEL) != static_cast<ccHObject*>(selectedIndexes[0].internalPointer())->isA(CC_2D_LABEL))
						{
							ccLog::Warning("[Selection] Labels and other entities can't be mixed! (release the CTRL key to start a new selection)");
							return;
						}
					}
				}
				selectionModel->select(selectedIndex,QItemSelectionModel::Toggle);
			}
			else
			{
				if (selectionModel->isSelected(selectedIndex))  //nothing to do
					return;
				selectionModel->select(selectedIndex,QItemSelectionModel::ClearAndSelect);
			}

			//hack: auto-scroll to selected element
			if (obj->isSelected() && !ctrlPushed)
				m_dbTreeWidget->scrollTo(selectedIndex);
		}
	}
	//otherwise we clear current selection (if CTRL is not pushed)
	else if (!ctrlPushed)
	{
		selectionModel->clear();
	}
}
コード例 #22
0
ファイル: localview.cpp プロジェクト: caidongyun/nullfxp
void LocalView::slot_mkdir()
{
    QString dir_name;
    QItemSelectionModel *ism = this->curr_item_view->selectionModel();
    QModelIndex cidx, idx;

    // QModelIndexList mil;
    if (ism == 0 || !ism->hasSelection()) {
        // qDebug()<<" selectedIndexes count :"<< mil.count() << " why no item selected????";
        qDebug()<<" selectedIndexes count :"<< ism->hasSelection() << " why no item selected????";
        QMessageBox::critical(this, tr("Warning..."), tr("No item selected"));
        return;
    }

    // mil = ism->selectedIndexes() ;
    cidx = ism->currentIndex();
    idx = ism->model()->index(cidx.row(), 0, cidx.parent());

    // QModelIndex midx = mil.at(0);
    QModelIndex midx = idx;
    QModelIndex aim_midx = (this->curr_item_view == this->uiw->treeView)
        ? this->dir_file_model->mapToSource(midx): midx;

    //检查所选择的项是不是目录
    if (!this->model->isDir(aim_midx)) {
        QMessageBox::critical(this, tr("Warning..."), tr("The selected item is not a directory."));
        return;
    }
    
    dir_name = QInputDialog::getText(this, tr("Create directory:"),
                                     tr("Input directory name:").leftJustified(80, ' '),
                                     QLineEdit::Normal, tr("new_direcotry"));
    if (dir_name == QString::null) {
        return;
    } 
    if (dir_name.length () == 0) {
        // qDebug()<<" selectedIndexes count :"<< mil.count() << " why no item selected????";
        qDebug()<<" selectedIndexes count :"<< ism->hasSelection() << " why no item selected????";
        QMessageBox::critical(this, tr("Warning..."), tr("No directory name supplyed."));
        return;
    }

    if (!QDir().mkdir(this->model->filePath(aim_midx) + "/" + dir_name)) {
        QMessageBox::critical(this, tr("Warning..."), tr("Create directory faild."));
    } else {
        this->slot_refresh_directory_tree();
    }
}
コード例 #23
0
//-----------------------------------------------------------------------------
void SetupTabMatrix::on_tableViewOperations_customContextMenuRequested(const QPoint &point)
{
    QModelIndex index = this->ui->tableViewOperations->indexAt(point);
    QItemSelectionModel *selection = this->ui->tableViewOperations->selectionModel();

    if (this->mMenu != NULL)
    {
        delete this->mMenu;
        this->mMenu = NULL;
    }

    if (index.isValid())
    {
        MatrixPreviewModel::RowType type = this->mMatrixModel->rowType(index.row());
        QModelIndexList list = selection->selectedIndexes();

        switch (type)
        {
        case MatrixPreviewModel::Source:
        {
            bool found = false;
            for (int i = 0; i < list.length() && !found; i++)
            {
                if (list.at(i).row() == 0)
                    found = true;
            }
            if (found)
            {
                this->mMenu = new QMenu(tr("Source"), this);

                QMenu *left = new QMenu(tr("Add \"Left Shift\""), this->mMenu);
                QMenu *right = new QMenu(tr("Add \"Right Shift\""), this->mMenu);

                this->mMenu->addMenu(left);
                this->mMenu->addMenu(right);

                for (int i = 0; i < 32; i++)
                {
                    QAction *action = left->addAction(QString("<< %1").arg(i), this, SLOT(operationAdd()));
                    action->setData(QVariant(-i));

                    action = right->addAction(QString(">> %1").arg(i), this, SLOT(operationAdd()));
                    action->setData(QVariant(i));
                }

                this->mMenu->exec(this->ui->tableViewOperations->mapToGlobal(point));
            }
            break;
        }
        case MatrixPreviewModel::Operation:
        {
                this->mMenu = new QMenu(tr("Operation"), this);

                int operationIndex = index.row() - 1;

                quint32 mask;
                int shift;
                bool left;

                this->mPreset->matrix()->operation(operationIndex, &mask, &shift, &left);

                QAction *actionLeft = this->mMenu->addAction(tr("Shift left"), this, SLOT(operationShift()));
                QAction *actionRight = this->mMenu->addAction(tr("Shift right"), this, SLOT(operationShift()));
                QAction *actionRemove = this->mMenu->addAction(tr("Remove"), this, SLOT(operationRemove()));
                Q_UNUSED(actionRemove)

                quint32 data = operationIndex;

                actionLeft->setData(QVariant(data | 0x80000000));
                actionRight->setData(QVariant(data));
                actionRemove->setData(QVariant(data));

                if (shift >= 31)
                {
                    if (left)
                        actionLeft->setEnabled(false);
                    else
                        actionRight->setEnabled(false);
                }

                this->mMenu->exec(this->ui->tableViewOperations->mapToGlobal(point));
            break;
        }
        case MatrixPreviewModel::MaskUsed:
        case MatrixPreviewModel::MaskAnd:
        case MatrixPreviewModel::MaskOr:
        case MatrixPreviewModel::MaskFill:
        {
            this->mMenu = new QMenu(tr("Mask"), this);

            quint32 data = (quint32)type;

            quint32 bits = 0;
            for (int i = 0; i < list.length(); i++)
            {
                if (list.at(i).row() == index.row())
                {
                    bits |= 0x00000001 << (31 - list.at(i).column());
                }
            }

            // show menu if more than 0 bits was selected
            if (bits != 0)
            {
                QList<QVariant> parameters;
                parameters.append(QVariant(data));
                parameters.append(QVariant(bits));
                parameters.append(QVariant(true));

                QAction *actionSet = this->mMenu->addAction(tr("Set 1"), this, SLOT(maskReset()));
                actionSet->setData(parameters);

                QAction *actionReset = this->mMenu->addAction(tr("Set 0"), this, SLOT(maskReset()));
                parameters.replace(2, QVariant(false));
                actionReset->setData(parameters);
            }

            this->mMenu->exec(this->ui->tableViewOperations->mapToGlobal(point));
            break;
        }
        default:
            break;
        }
    }
}
コード例 #24
0
void MusicListView::showContextMenu(const QPoint &pos,
                                    PlaylistPtr selectedPlaylist,
                                    PlaylistPtr favPlaylist,
                                    QList<PlaylistPtr> newPlaylists)
{
    Q_D(MusicListView);
    QItemSelectionModel *selection = this->selectionModel();

    if (selection->selectedRows().length() <= 0) {
        return;
    }

    QPoint globalPos = this->mapToGlobal(pos);

    QMenu playlistMenu;
    playlistMenu.setStyle(QStyleFactory::create("dlight"));

    auto newvar = QVariant::fromValue(PlaylistPtr());

    auto createPlaylist = playlistMenu.addAction(tr("New playlist"));
    createPlaylist->setData(newvar);
    createPlaylist->setIcon(QIcon(":/light/image/plus.svg"));

    playlistMenu.addSeparator();

    if (selectedPlaylist != favPlaylist) {
        auto act = playlistMenu.addAction(favPlaylist->displayName());
        act->setData(QVariant::fromValue(favPlaylist));
    }

    for (auto playlist : newPlaylists) {
        QFont font(playlistMenu.font());
        QFontMetrics fm(font);
        auto text = fm.elidedText(QString(playlist->displayName().replace("&", "&&")),
                                  Qt::ElideMiddle, 160);
        auto act = playlistMenu.addAction(text);
        act->setData(QVariant::fromValue(playlist));
    }

    connect(&playlistMenu, &QMenu::triggered, this, [ = ](QAction * action) {
        auto playlist = action->data().value<PlaylistPtr >();
        qDebug() << playlist;
        MetaPtrList metalist;
        for (auto &index : selection->selectedRows()) {
            auto meta = d->model->meta(index);
            if (!meta.isNull()) {
                metalist << meta;
            }
        }
        Q_EMIT addToPlaylist(playlist, metalist);
    });

    bool singleSelect = (1 == selection->selectedRows().length());

    QMenu myMenu;
    myMenu.setStyle(QStyleFactory::create("dlight"));

    QAction *playAction = nullptr;
    if (singleSelect) {
        playAction = myMenu.addAction(tr("Play"));
    }
    myMenu.addAction(tr("Add to playlist"))->setMenu(&playlistMenu);
    myMenu.addSeparator();

    QAction *displayAction = nullptr;
    if (singleSelect) {
        displayAction = myMenu.addAction(tr("Display in file manager"));
    }

    auto removeAction = myMenu.addAction(tr("Remove from playlist"));
    auto deleteAction = myMenu.addAction(tr("Delete from local disk"));

    QAction *songAction = nullptr;

    QMenu textCodecMenu;
    textCodecMenu.setStyle(QStyleFactory::create("dlight"));

    if (singleSelect) {
        auto index = selection->selectedRows().first();
        auto meta = d->model->meta(index);
        QList<QByteArray> codecList = DMusic::detectMetaEncodings(meta);
//        codecList << "utf-8" ;
        for (auto codec : codecList) {
            auto act = textCodecMenu.addAction(codec);
            act->setData(QVariant::fromValue(codec));
        }

        if (codecList.length() > 1) {
            myMenu.addSeparator();
            myMenu.addAction(tr("Encoding"))->setMenu(&textCodecMenu);
        }

        myMenu.addSeparator();
        songAction = myMenu.addAction(tr("Song info"));

        connect(&textCodecMenu, &QMenu::triggered, this, [ = ](QAction * action) {
            auto codec = action->data().toByteArray();
            meta->updateCodec(codec);
            Q_EMIT updateMetaCodec(meta);
        });
    }

    if (playAction) {
        connect(playAction, &QAction::triggered, this, [ = ](bool) {
            auto index = selection->selectedRows().first();
            Q_EMIT playMedia(d->model->meta(index));
        });
    }

    if (displayAction) {
        connect(displayAction, &QAction::triggered, this, [ = ](bool) {
            auto index = selection->selectedRows().first();
            auto meta = d->model->meta(index);
            auto dirUrl = QUrl::fromLocalFile(meta->localPath);
            Dtk::Widget::DDesktopServices::showFileItem(dirUrl);
        });
    }

    if (removeAction) {
        connect(removeAction, &QAction::triggered, this, [ = ](bool) {
            d->removeSelection(selection);
        });
    }

    if (deleteAction) {
        connect(deleteAction, &QAction::triggered, this, [ = ](bool) {
            bool containsCue = false;
            MetaPtrList metalist;
            for (auto index : selection->selectedRows()) {
                auto meta = d->model->meta(index);
                if (!meta->cuePath.isEmpty()) {
                    containsCue = true;
                }
                metalist << meta;
            }

            Dtk::Widget::DDialog warnDlg(this);
            warnDlg.setStyle(QStyleFactory::create("dlight"));
            warnDlg.setTextFormat(Qt::RichText);
            warnDlg.addButton(tr("Cancel"), true, Dtk::Widget::DDialog::ButtonWarning);
            warnDlg.addButton(tr("Delete"), false, Dtk::Widget::DDialog::ButtonNormal);

            auto cover = QImage(QString(":/common/image/del_notify.svg"));
            if (1 == metalist.length()) {
                auto meta = metalist.first();
                auto coverData = MetaSearchService::coverData(meta);
                if (coverData.length() > 0) {
                    cover = QImage::fromData(coverData);
                }
                warnDlg.setMessage(QString(tr("Are you sure you want to delete %1?")).arg(meta->title));
            } else {
                warnDlg.setMessage(QString(tr("Are you sure you want to delete the selected %1 songs?")).arg(metalist.length()));
            }

            if (containsCue) {
                warnDlg.setTitle(tr("Are you sure you want to delete the selected %1 songs?").arg(metalist.length()));
                warnDlg.setMessage(tr("Deleting the current song will also delete the song files contained"));
            }
            auto coverPixmap =  QPixmap::fromImage(WidgetHelper::cropRect(cover, QSize(64, 64)));

            warnDlg.setIcon(QIcon(coverPixmap));
            if (0 == warnDlg.exec()) {
                return;
            }
            Q_EMIT deleteMusicList(metalist);
        });
    }

    if (songAction) {
        connect(songAction, &QAction::triggered, this, [ = ](bool) {
            auto index = selection->selectedRows().first();
            auto meta = d->model->meta(index);
            Q_EMIT showInfoDialog(meta);
        });
    }

    myMenu.exec(globalPos);
}
コード例 #25
0
void SpecialOrderEditor::addItem()
{
  double dqty = 1; //if not any value, default is ONE
  QStringList msgP;
  QStringList msgU;
  int incTime = 0;
  Azahar *myDb = new Azahar;
  myDb->setDatabase(db);
  
  if (!ui->editAddQty->text().isEmpty()) {
    dqty = ui->editAddQty->text().toDouble();
  }
  //get selected items from source view
  QItemSelectionModel *selectionModel = ui->sourcePView->selectionModel();
  QModelIndexList indexList = selectionModel->selectedRows(); // pasar el indice que quiera (0=code, 1=name)
  foreach(QModelIndex index, indexList) {
    qulonglong code    = index.data().toULongLong();
    QString    codeStr = index.data().toString();
    bool exists = false;
    ProductInfo pInfo;
    //get product info from hash or db
    if (groupInfo.productsList.contains(code)) {
      pInfo = groupInfo.productsList.take(code);
      //check measures for the product
      if (pInfo.units == 1 ) { //by pieces
        QString tmpStr = ui->editAddQty->text();
        if (tmpStr.endsWith(".00")) tmpStr.chop(3); //discard .00's
        if (tmpStr.endsWith(".0")) tmpStr.chop(2);//discard .00's
        if (tmpStr.contains(".") || tmpStr.contains(",")) {
          int tmp = dqty;
          dqty = tmp; //pass to integer instead of double
          msgP.append(i18n("<i>%1</i> rounded to %2",pInfo.desc,tmp));
          incTime += 1000;
        }
      }
      if (pInfo.stockqty >= pInfo.qtyOnList+dqty)
        pInfo.qtyOnList += dqty; //increment it
      else {
        incTime += 1000;
        msgU.append(i18n("<i>%1</i> <b>requested %2, on stock %3</b><br>", pInfo.desc,dqty,pInfo.stockqty));
      }
      //if not enough, its not incremented.
      exists = true;
    } else {
      pInfo = myDb->getProductInfo(codeStr);
      //check measures for the product
      if (pInfo.units == 1) { //by pieces
        QString tmpStr = ui->editAddQty->text();
        if (tmpStr.endsWith(".00")) tmpStr.chop(3);//discard .00's
        if (tmpStr.endsWith(".0")) tmpStr.chop(2);//discard .00's
        if (tmpStr.contains(".") || tmpStr.contains(",")) {
          int tmp = dqty;
          dqty = tmp; //pass to integer instead of double
          msgP.append(i18n("<i>%1</i> rounded to %2",pInfo.desc,tmp));
          incTime += 1000;
        }
      }
      pInfo.qtyOnList = 0;
      if (pInfo.stockqty >= dqty)
        pInfo.qtyOnList = dqty;
      else {
        incTime += 1000;
        msgU.append(i18n("<i>%1</i> <b>requested %2, on stock %3</b><br>", pInfo.desc,dqty,pInfo.stockqty));
      }
    }

    // Insert/Update GroupView
    if (!exists) {
      //check if it is available.
      if (pInfo.qtyOnList <= 0 ) {
        //NO, its not available.
        continue;
        qDebug()<<"Continue...";
      }
      // Insert into the groupView
      int rowCount = ui->groupView->rowCount();
      ui->groupView->insertRow(rowCount);
      ui->groupView->setItem(rowCount, 0, new QTableWidgetItem(QString::number(dqty)));
      ui->groupView->setItem(rowCount, 1, new QTableWidgetItem(pInfo.desc));
    } else {
      if (pInfo.qtyOnList <= 0 ) {
        //NO, its not available.
        continue;
        qDebug()<<"Continue...";
      }
      //simply update the groupView with the new qty
      for (int ri=0; ri<ui->groupView->rowCount(); ++ri)
      {
        QTableWidgetItem * item = ui->groupView->item(ri, 1);
        QString name = item->data(Qt::DisplayRole).toString();
        if (name == pInfo.desc) {
          //update
          QTableWidgetItem *itemQ = ui->groupView->item(ri, 0);//item qty
          itemQ->setData(Qt::EditRole, QVariant(pInfo.qtyOnList));
          continue;
        }
      }
    }
    // update info of the group
    groupInfo.count = groupInfo.count+dqty;
    groupInfo.cost  += pInfo.cost*dqty;  //pInfo.qtyOnList;
    groupInfo.price += pInfo.price*dqty; //pInfo.qtyOnList;
    //NOTE:group price is not affected by any product discount, it takes normal price.
    //     Discounts are taken into consideration after adding to the purchase list, when calculating taxes and price for the SO.
    bool yes = false;
    if (pInfo.stockqty >= dqty )
      yes = true;
    groupInfo.isAvailable = (groupInfo.isAvailable && yes );
    // Insert product to the group hash
    groupInfo.productsList.insert(code, pInfo);
    if (!yes) {
      //Just warning!... the insert into the view is above...
      qDebug()<<"Product is not available!";
    }
  }
コード例 #26
0
ファイル: settingsdialog.cpp プロジェクト: FengJianjian/zeal
SettingsDialog::SettingsDialog(Core::Application *app, ListModel *listModel, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SettingsDialog()),
    m_application(app),
    m_docsetRegistry(app->docsetRegistry())
{
    ui->setupUi(this);

#ifdef Q_OS_OSX
    ui->availableDocsetList->setAttribute(Qt::WA_MacShowFocusRect, false);
    ui->installedDocsetList->setAttribute(Qt::WA_MacShowFocusRect, false);
#endif

    ui->downloadableGroup->hide();
    ui->docsetsProgress->hide();

    ui->installedDocsetList->setItemDelegate(new DocsetListItemDelegate(this));
    ui->installedDocsetList->setModel(listModel);

    ui->installedDocsetList->setSelectionMode(QAbstractItemView::ExtendedSelection);
    QItemSelectionModel *selectionModel = ui->installedDocsetList->selectionModel();
    connect(selectionModel, &QItemSelectionModel::selectionChanged,
            [this, selectionModel]() {
        if (!m_replies.isEmpty())
            return;

        ui->removeDocsetsButton->setEnabled(selectionModel->hasSelection());

        for (const QModelIndex &index : selectionModel->selectedIndexes()) {
            if (index.data(Zeal::ListModel::UpdateAvailableRole).toBool()) {
                ui->updateSelectedDocsetsButton->setEnabled(true);
                return;
            }
        }
        ui->updateSelectedDocsetsButton->setEnabled(false);
    });
    connect(ui->updateSelectedDocsetsButton, &QPushButton::clicked,
            this, &SettingsDialog::updateSelectedDocsets);
    connect(ui->updateAllDocsetsButton, &QPushButton::clicked,
            this, &SettingsDialog::updateAllDocsets);
    connect(ui->removeDocsetsButton, &QPushButton::clicked,
            this, &SettingsDialog::removeSelectedDocsets);

    ui->availableDocsetList->setItemDelegate(new ProgressItemDelegate(this));

    // Setup signals & slots
    connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &SettingsDialog::saveSettings);
    connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &SettingsDialog::loadSettings);
    connect(ui->buttonBox, &QDialogButtonBox::clicked, this, [this](QAbstractButton *button) {
        if (button == ui->buttonBox->button(QDialogButtonBox::Apply))
            saveSettings();
    });

    connect(ui->minFontSize, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
            this, [](int value) {
        QWebSettings::globalSettings()->setFontSize(QWebSettings::MinimumFontSize, value);
    });

    connect(ui->addFeedButton, &QPushButton::clicked, this, &SettingsDialog::addDashFeed);
    connect(ui->refreshButton, &QPushButton::clicked, this, &SettingsDialog::downloadDocsetList);

    connect(m_application, &Core::Application::extractionCompleted,
            this, &SettingsDialog::extractionCompleted);
    connect(m_application, &Core::Application::extractionError,
            this, &SettingsDialog::extractionError);
    connect(m_application, &Core::Application::extractionProgress,
            this, &SettingsDialog::extractionProgress);

    loadSettings();
}
コード例 #27
0
ファイル: historyform.cpp プロジェクト: huggle/huggle3-qt-lx
void HistoryForm::onTick01()
{
    if (this->CurrentEdit == nullptr)
        throw new Huggle::NullPointerException("local WikiEdit CurrentEdit", BOOST_CURRENT_FUNCTION);

    if (this->RetrievingEdit && this->RetrievedEdit != nullptr)
    {
        if (this->RetrievedEdit->IsPostProcessed())
        {
            MainWindow::HuggleMain->ProcessEdit(this->RetrievedEdit, false, true);
            this->RetrievingEdit = false;
            this->RetrievedEdit = nullptr;
            this->t1->stop();
            this->MakeSelectedRowBold();
            MainWindow::HuggleMain->wEditBar->RefreshPage();
        }
        return;
    }

    if (this->query == nullptr || !this->query->IsProcessed())
        return;

    if (this->query->IsFailed())
    {
        this->ui->pushButton->setEnabled(true);
        Huggle::Syslog::HuggleLogs->ErrorLog(_l("history-failure"));
        this->query = nullptr;
        this->t1->stop();
        return;
    }
    bool IsLatest = false;
    QList<ApiQueryResultNode*> revision_data = this->query->GetApiQueryResult()->GetNodes("rev");
    int x = 0;
    while (x < revision_data.count())
    {
        ApiQueryResultNode *rv = revision_data.at(x);
        WikiPageHistoryItem *item = new WikiPageHistoryItem(this->query->GetSite());
        if (rv->Attributes.contains("revid"))
        {
            item->RevID = rv->GetAttribute("revid");
        }
        else
        {
            x++;
            continue;
        }
        bool founder = false;
        item->Name = this->CurrentEdit->Page->PageName;
        item->Site = this->CurrentEdit->GetSite();
        if (rv->Attributes.contains("user"))
            item->User = rv->GetAttribute("user");
        if (rv->Attributes.contains("size"))
            item->Size = rv->GetAttribute("size");
        if (rv->Attributes.contains("timestamp"))
            item->Date = rv->GetAttribute("timestamp");
        if (rv->Attributes.contains("comment") && !rv->GetAttribute("comment").isEmpty())
            item->Summary = rv->GetAttribute("comment");
        this->ui->tableWidget->insertRow(x);
        QIcon icon(":/huggle/pictures/Resources/blob-none.png");
        if (this->CurrentEdit->Page->FounderKnown() && WikiUser::CompareUsernames(item->User, this->CurrentEdit->Page->GetFounder()))
            founder = true;
        if (WikiUtil::IsRevert(item->Summary))
        {
            item->Type = EditType_Revert;
            icon = QIcon(":/huggle/pictures/Resources/blob-revert.png");
        }
        else if (WikiUser::IsIPv6(item->User) || WikiUser::IsIPv4(item->User))
        {
            item->Type = EditType_Anon;
            icon = QIcon(":/huggle/pictures/Resources/blob-anon.png");
        }
        else if (this->CurrentEdit->GetSite()->GetProjectConfig()->WhiteList.contains(item->User))
        {
            item->Type = EditType_W;
            icon = QIcon(":/huggle/pictures/Resources/blob-ignored.png");
        }
        WikiUser *wu = WikiUser::RetrieveUser(item->User, item->Site);
        if (wu != nullptr)
        {
            if (wu->IsReported)
            {
                item->Type = EditType_Reported;
                icon = QIcon(":/huggle/pictures/Resources/blob-reported.png");
            }
            else if (wu->GetWarningLevel() > 0)
            {
                switch (wu->GetWarningLevel())
                {
                case 1:
                    item->Type = EditType_1;
                    icon = QIcon(":/huggle/pictures/Resources/blob-warn-1.png");
                    break;
                case 2:
                    item->Type = EditType_2;
                    icon = QIcon(":/huggle/pictures/Resources/blob-warn-2.png");
                    break;
                case 3:
                    item->Type = EditType_3;
                    icon = QIcon(":/huggle/pictures/Resources/blob-warn-3.png");
                    break;
                case 4:
                    item->Type = EditType_4;
                    icon = QIcon(":/huggle/pictures/Resources/blob-warn-4.png");
                    break;
                }
            }
        }
        bool selected = this->CurrentEdit->RevID == item->RevID.toInt();
        if (selected && x == 0)
            IsLatest = true;
        item->IsCurrent = true;
        if (selected)
            this->SelectedRow = x;
        QFont font;
        font.setItalic(founder);
        font.setBold(selected);
        QTableWidgetItem *i = new QTableWidgetItem(icon, "");
        this->ui->tableWidget->setItem(x, 0, i);
        i = new QTableWidgetItem(item->User);
        i->setFont(font);
        this->ui->tableWidget->setItem(x, 1, i);
        i = new QTableWidgetItem(item->Size);
        i->setFont(font);
        this->ui->tableWidget->setItem(x, 2, i);
        i = new QTableWidgetItem(item->Summary);
        i->setFont(font);
        this->ui->tableWidget->setItem(x, 3, i);
        i = new QTableWidgetItem(item->Date);
        i->setFont(font);
        this->ui->tableWidget->setItem(x, 4, i);
        i = new QTableWidgetItem(item->RevID);
        i->setFont(font);
        this->ui->tableWidget->setItem(x, 5, i);
        this->Items.append(item);
        x++;
    }
    this->ui->tableWidget->resizeRowsToContents();
    this->query = nullptr;
    this->t1->stop();
    if (!this->CurrentEdit->NewPage && !Configuration::HuggleConfiguration->ForceNoEditJump && !IsLatest)
    {
        if (Configuration::HuggleConfiguration->UserConfig->LastEdit)
        {
            this->Display(0, Resources::Html_StopFire, true);
            return;
        }
        else
        {
            QPoint pntr(0, this->pos().y());
            if (this->pos().x() > 400)
                pntr.setX(this->pos().x() - 200);
            else
                pntr.setX(this->pos().x() + 100);

            if (hcfg->UserConfig->ShowWarningIfNotOnLastRevision)
                QToolTip::showText(pntr, "<b><big>" + _l("historyform-not-latest-tip") + "</big></b>", this);
        }
    }
    if (hcfg->UserConfig->AutomaticallyGroup)
    {
        // Check if edits made around of this one weren't made by same user
        // in case they were we need to display a range of them
        QString user = this->CurrentEdit->User->Username;
        int RangeStart = this->SelectedRow;
        int RangeEnd = this->SelectedRow;
        int row = this->SelectedRow;
        while (row > 0)
        {
            if (user != this->ui->tableWidget->item(row - 1, 1)->text())
                break;
            row--;
        }
        RangeStart = row;
        row = this->SelectedRow;
        while (row < (this->ui->tableWidget->rowCount() - 1))
        {
            if (user != this->ui->tableWidget->item(row + 1, 1)->text())
                break;
            row++;
        }
        RangeEnd = row;
        if (RangeStart != RangeEnd)
        {
            QItemSelectionModel *selectionModel = this->ui->tableWidget->selectionModel();
            row = RangeStart;
            this->IgnoreSelectionChanges = true;
            this->ui->tableWidget->clearSelection();
            QItemSelection itemSelection = selectionModel->selection();
            while (row <= RangeEnd)
            {
                this->ui->tableWidget->selectRow(row++);
                itemSelection.merge(selectionModel->selection(), QItemSelectionModel::Select);
            }
            selectionModel->clearSelection();
            this->IgnoreSelectionChanges = false;
            selectionModel->select(itemSelection, QItemSelectionModel::Select);
        }
    }
    this->IgnoreSelectionChanges = false;
    MainWindow::HuggleMain->wEditBar->RefreshPage();
}
コード例 #28
0
ファイル: listview.cpp プロジェクト: amottola/slew
void
ListView_Impl::paintDropTarget(QPainter *painter, const QModelIndex& index, int where)
{
	QStyleOptionViewItem option = viewOptions();
	QRect rect = this->visualRect(index);
	QWidget *viewport = this->viewport();
	QColor highlight = palette().color(QPalette::HighlightedText);
	QColor color = option.state & QStyle::State_Selected ? highlight : palette().color(QPalette::Highlight);
	QPen pen(color);
	
	painter->save();
	
	if (!index.isValid())
		where = SL_EVENT_DRAG_ON_VIEWPORT;
	
	switch (where) {
	case SL_EVENT_DRAG_BELOW_ITEM:
	case SL_EVENT_DRAG_ABOVE_ITEM:
		{
			if (viewMode() == IconMode) {
				QSize size = gridSize();
				if (size.isEmpty())
					size = rect.size();
				int x, y, height = size.height();
				int cellWidth = size.width() + spacing();
				int cellHeight = height + spacing();
				
				x = rect.left() + horizontalOffset();
				if (where == SL_EVENT_DRAG_BELOW_ITEM)
					x += cellWidth;
				x = ((x / cellWidth) * cellWidth) - horizontalOffset();
				y = (((rect.top() + verticalOffset()) / cellHeight) * cellHeight) - verticalOffset();
				height = qMax(5, height - 5);
				
				painter->setRenderHint(QPainter::Antialiasing);
				
				pen.setWidth(3);
				pen.setColor(highlight);
				painter->setPen(pen);
				painter->drawEllipse(QPointF(x, y + height), 3, 3);
				painter->drawLine(x, y + 5, x, y + height - 3);
				
				pen.setWidth(2);
				pen.setColor(color);
				painter->setPen(pen);
				painter->drawEllipse(QPointF(x, y + height), 3, 3);
				painter->drawLine(x, y + 5, x, y + height - 3);
			}
			else {
				int x, y, width;
				
				if (where == SL_EVENT_DRAG_BELOW_ITEM)
					y = rect.bottom() + 1;
				else
					y = rect.top();
				x = rect.left();
				width = viewport->width() - rect.left() - 10;
				
				painter->setRenderHint(QPainter::Antialiasing);
				
				pen.setWidth(3);
				pen.setColor(highlight);
				painter->setPen(pen);
				painter->drawEllipse(QPointF(x + width, y), 3, 3);
				painter->drawLine(x, y, x + width - 3, y);
				
				pen.setWidth(2);
				pen.setColor(color);
				painter->setPen(pen);
				painter->drawEllipse(QPointF(x + width, y), 3, 3);
				painter->drawLine(x, y, x + width - 3, y);
			}
		}
		break;
	
	case SL_EVENT_DRAG_ON_ITEM:
		{
			option.rect = rect;
			rect.adjust(1, 1, -1, -1);
			
			painter->setRenderHint(QPainter::Antialiasing);
			int radius = qMin(8, rect.height() / 2);
			
			pen.setWidth(3);
			pen.setColor(highlight);
			painter->setPen(pen);
			painter->drawRoundedRect(rect, radius, radius);

			pen.setWidth(2);
			
			if (viewMode() == IconMode) {
				color = palette().color(QPalette::Inactive, QPalette::Highlight);
				pen.setColor(color);
				painter->setPen(pen);
				painter->setBrush(QBrush(color));
				painter->drawRoundedRect(rect, radius, radius);
				
				QItemSelectionModel *selection = selectionModel();
				
				if ((selection) && (selection->isSelected(index)))
					option.state |= QStyle::State_Selected;
				if (!(model()->flags(index) & Qt::ItemIsEnabled))
					option.state &= ~QStyle::State_Enabled;
				if (option.state & QStyle::State_Enabled)
					option.palette.setCurrentColorGroup(QPalette::Normal);
				else
					option.palette.setCurrentColorGroup(QPalette::Disabled);
				itemDelegate(index)->paint(painter, option, index);
			}
			else {
				pen.setColor(color);
				painter->setPen(pen);
				painter->drawRoundedRect(rect, radius, radius);
			}
		}
		break;
		
	case SL_EVENT_DRAG_ON_VIEWPORT:
		{
			rect = viewport->rect();
			rect.adjust(0, 0, -1, -1);
			
			painter->setRenderHint(QPainter::Antialiasing, false);
			
			pen.setWidth(5);
			pen.setColor(highlight);
			painter->setPen(pen);
			painter->drawRect(rect);
			
			pen.setWidth(3);
			pen.setColor(color);
			painter->setPen(pen);
			painter->drawRect(rect);
		}
		break;
	}
	
	painter->restore();
}
コード例 #29
0
ファイル: PartitionPage.cpp プロジェクト: dgikiller/calamares
void
PartitionPage::updateFromCurrentDevice()
{
    QModelIndex index = m_core->deviceModel()->index( m_ui->deviceComboBox->currentIndex(), 0 );
    if ( !index.isValid() )
        return;

    Device* device = m_core->deviceModel()->deviceForIndex( index );

    QAbstractItemModel* oldModel = m_ui->partitionTreeView->model();
    if ( oldModel )
        disconnect( oldModel, 0, this, 0 );

    PartitionModel* model = m_core->partitionModelForDevice( device );
    m_ui->partitionBarsView->setModel( model );
    m_ui->partitionLabelsView->setModel( model );
    m_ui->partitionTreeView->setModel( model );
    m_ui->partitionTreeView->expandAll();

    // Make all views use the same selection model.
    if ( m_ui->partitionBarsView->selectionModel() !=
         m_ui->partitionTreeView->selectionModel() ||
         m_ui->partitionBarsView->selectionModel() !=
         m_ui->partitionLabelsView->selectionModel() )
    {
        // Tree view
        QItemSelectionModel* selectionModel = m_ui->partitionTreeView->selectionModel();
        m_ui->partitionTreeView->setSelectionModel( m_ui->partitionBarsView->selectionModel() );
        selectionModel->deleteLater();

        // Labels view
        selectionModel = m_ui->partitionLabelsView->selectionModel();
        m_ui->partitionLabelsView->setSelectionModel( m_ui->partitionBarsView->selectionModel() );
        selectionModel->deleteLater();
    }

    // This is necessary because even with the same selection model it might happen that
    // a !=0 column is selected in the tree view, which for some reason doesn't trigger a
    // timely repaint in the bars view.
    connect( m_ui->partitionBarsView->selectionModel(), &QItemSelectionModel::currentChanged,
             this, [=]
    {
        QModelIndex selectedIndex = m_ui->partitionBarsView->selectionModel()->currentIndex();
        selectedIndex = selectedIndex.sibling( selectedIndex.row(), 0 );
        m_ui->partitionBarsView->setCurrentIndex( selectedIndex );
        m_ui->partitionLabelsView->setCurrentIndex( selectedIndex );
    }, Qt::UniqueConnection );

    // Must be done here because we need to have a model set to define
    // individual column resize mode
    QHeaderView* header = m_ui->partitionTreeView->header();
    header->setSectionResizeMode( QHeaderView::ResizeToContents );
    header->setSectionResizeMode( 0, QHeaderView::Stretch );

    updateButtons();
    // Establish connection here because selection model is destroyed when
    // model changes
    connect( m_ui->partitionTreeView->selectionModel(), &QItemSelectionModel::currentChanged,
             [ this ]( const QModelIndex& index, const QModelIndex& oldIndex )
    {
        updateButtons();
    } );
    connect( model, &QAbstractItemModel::modelReset, this, &PartitionPage::onPartitionModelReset );
}
コード例 #30
0
ファイル: categorydialog.cpp プロジェクト: bywyu/rexloader
void CategoryDialog::applyCategory()
{
    QSqlQuery qr(mydb);

    if(internal_id == -1)
    {
        int parent_id = 1;
        QModelIndex parent = model->index(0,0);
        QItemSelectionModel *selection = ui->treeView->selectionModel();

        parent = selection->selectedIndexes().value(0,parent);
        parent_id = model->data(model->index(parent.row(), 1, parent.parent()),100).toInt();

        qr.prepare("INSERT INTO categories(title, dir, extlist, parent_id) VALUES (:title, :dir, :extlist, :parent)");
        qr.bindValue("title", ui->cattitle->text());
        qr.bindValue("dir", ui->catpath->text());
        qr.bindValue("extlist", ui->textEdit->document()->toPlainText());
        qr.bindValue("parent", parent_id);

        if(!qr.exec())
        {
            //Запись в журнал ошибок
            qDebug()<<"void CategoryDialog::applyCategory(1): SQL:" + qr.executedQuery() + " Error: " + qr.lastError().text();
            return;
        }

        myrow =  model->rowCount(parent);

        emit canUpdateModel(ui->cattitle->text(), myrow, parent_id, 0);

        QPushButton *btn = qobject_cast<QPushButton*>(sender());
        if(btn == ui->buttonBox->button(QDialogButtonBox::Ok))accept();
        else
        {
            ui->treeView->setEnabled(false);
            qr.clear();
            qr.prepare("SELECT id FROM categories WHERE title=:title AND parent_id=:parent");
            qr.bindValue("title", ui->cattitle->text());
            qr.bindValue("parent",parent_id);

            if(!qr.exec())
            {
                //Запись в журнал ошибок
                qDebug()<<"void CategoryDialog::applyCategory(2): SQL:" + qr.executedQuery() + " Error: " + qr.lastError().text();
                accept();
                return;
            }

            qr.next();
            internal_id = qr.value(0).toInt();
            myparent_id = parent_id;
        }
        return;
    }

    qr.prepare("UPDATE categories SET title=:title, dir=:dir, extlist=:ext WHERE id=:id");
    qr.bindValue("title", ui->cattitle->text());
    qr.bindValue("dir", ui->catpath->text());
    qr.bindValue("ext", ui->textEdit->document()->toPlainText());
    qr.bindValue("id", internal_id);

    if(!qr.exec())
    {
        //Запись в журнал ошибок
        qDebug()<<"void CategoryDialog::applyCategory(3): SQL:" + qr.executedQuery() + " Error: " + qr.lastError().text();
        accept();
        return;
    }

    emit canUpdateModel(QString(), myrow, myparent_id, internal_id);

    QPushButton *btn = qobject_cast<QPushButton*>(sender());
    if(btn == ui->buttonBox->button(QDialogButtonBox::Ok))accept();
}