/** * Retrieves the HTTP authentication username and password for a given host and realm pair. If * there are multiple username/password combinations for a host/realm, only the first one will * be returned. * * @param host the host the password applies to * @param realm the realm the password applies to * @return a String[] if found where String[0] is username (which can be null) and * String[1] is password. Null is returned if it can't find anything. */ AutoPtr< ArrayOf<String> > HttpAuthDatabase::GetHttpAuthUsernamePassword( /* [in] */ String host, /* [in] */ String realm) { if (host == NULL || realm == NULL || !WaitForInit()) { return NULL; } AutoPtr< ArrayOf<String> > columns = ArrayOf<String> >::Alloc(2); (*columns)[0] = HTTPAUTH_USERNAME_COL; (*columns)[1] = HTTPAUTH_PASSWORD_COL; String selection("("); selection += HTTPAUTH_HOST_COL; selection += " == ?) AND "; selection += "("; selection += HTTPAUTH_REALM_COL; selection += " == ?)"; AutoPtr< ArrayOf<String> > ret; AutoPtr<ICursor> cursor; // try { AutoPtr< ArrayOf<String> > hostRealm = ArrayOf<String>::Alloc(2); (*hostRealm)[0] = host; (*hostRealm)[1] = realm; mDatabase->Query(HTTPAUTH_TABLE_NAME, columns, selection, hostRealm, NULL, NULL, NULL, (ICursor**)&cursor); Boolean bMoveToFirst = FALSE; cursor->MoveToFirst(&bMoveToFirst); if (bMoveToFirst) { ret = ArrayOf<String>::Alloc(2); String str1, str2; Int32 index1, index2; cursor->GetColumnIndex(HTTPAUTH_USERNAME_COL, &index1); cursor->GetString(index1, &str1); cursor->GetColumnIndex(HTTPAUTH_USERNAME_COL, &index2); cursor->GetString(index2, &str2); (*ret)[0] = str1; (*ret)[1] = str2; } // } catch (IllegalStateException e) { // Log.e(LOGTAG, "getHttpAuthUsernamePassword", e); // } finally { // if (cursor != null) cursor.close(); // } return ret; }
void filtered_view_cmd (void) { char *command; command = input_dialog (_(" Filtered view "), _(" Filter command and arguments:"), selection (current_panel)->fname); if (!command) return; view (command, "", 0, 0); g_free (command); }
TEST_F(SelectionAdjusterTest, adjustSelectionInFlatTree) { setBodyContent("<div id=sample>foo</div>"); MockVisibleSelectionChangeObserver selectionObserver; VisibleSelectionInFlatTree selectionInFlatTree; selectionInFlatTree.setChangeObserver(selectionObserver); Node* const sample = document().getElementById("sample"); Node* const foo = sample->firstChild(); // Select "foo" VisibleSelection selection(Position(foo, 0), Position(foo, 3)); SelectionAdjuster::adjustSelectionInFlatTree(&selectionInFlatTree, selection); EXPECT_EQ(PositionInFlatTree(foo, 0), selectionInFlatTree.start()); EXPECT_EQ(PositionInFlatTree(foo, 3), selectionInFlatTree.end()); EXPECT_EQ(1, selectionObserver.callCounter()) << "adjustSelectionInFlatTree() should call didChangeVisibleSelection()"; }
void main() { int x[MAXSIZE],n, i; printf("\n Enter number of elements "); scanf("%d",&n); for (i = 0; i < n; i++) { printf("\n Enter element %d ",i+1); scanf("%d",&x[i]); } selection(x, n); printf("\n Sorted list is:\n\n"); for (i = 0; i < n; i++) printf("%d ", x[i]); printf("\n"); }
void main() { int n,a[50],i; printf("Enter the number of elements"); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } selection(a,n); for(i=0;i<n;i++) { printf("%d",a[i]); } return 0; }
void TimelineDock::setSelection(QList<int> newSelection, int trackIndex, bool isMultitrack) { if (newSelection != selection() || trackIndex != m_selection.selectedTrack || isMultitrack != m_selection.isMultitrackSelected) { LOG_DEBUG() << "Changing selection to" << newSelection << " trackIndex" << trackIndex << "isMultitrack" << isMultitrack; m_selection.selectedClips = newSelection; m_selection.selectedTrack = trackIndex; m_selection.isMultitrackSelected = isMultitrack; emit selectionChanged(); if (!m_selection.selectedClips.isEmpty()) emitSelectedFromSelection(); else emit selected(0); } }
void filtered_view_cmd (void) { char *command; command = input_dialog (_(" Filtered view "), _(" Filter command and arguments:"), MC_HISTORY_FM_FILTERED_VIEW, selection (current_panel)->fname); if (!command) return; mc_internal_viewer (command, "", NULL, 0); g_free (command); }
TEST_F(FrameSelectionTest, InvalidateCaretRect) { RefPtrWillBeRawPtr<Text> text = appendTextNode("Hello, World!"); document().view()->updateAllLifecyclePhases(); VisibleSelection validSelection(Position(text, 0), Position(text, 0)); setSelection(validSelection); selection().setCaretRectNeedsUpdate(); EXPECT_TRUE(selection().isCaretBoundsDirty()); selection().invalidateCaretRect(); EXPECT_FALSE(selection().isCaretBoundsDirty()); document().body()->removeChild(text); document().updateLayoutIgnorePendingStylesheets(); selection().setCaretRectNeedsUpdate(); EXPECT_TRUE(selection().isCaretBoundsDirty()); selection().invalidateCaretRect(); EXPECT_FALSE(selection().isCaretBoundsDirty()); }
void Matrix::copySelection() { QString text; int i,j; int rows=d_table->numRows(); int cols=d_table->numCols(); QMemArray<int> selection(1); int c=0; for (i=0;i<cols;i++) { if (d_table->isColumnSelected(i,TRUE)) { c++; selection.resize(c); selection[c-1]=i; } } if (c>0) { for (i=0; i<rows; i++) { for (j=0;j<c-1;j++) text+=d_table->text(i,selection[j])+"\t"; text+=d_table->text(i,selection[c-1])+"\n"; } } else { QTableSelection sel=d_table->selection(d_table->currentSelection()); int top=sel.topRow(); int bottom=sel.bottomRow(); int left=sel.leftCol(); int right=sel.rightCol(); for (i=top; i<=bottom; i++) { for (j=left; j<right; j++) text+=d_table->text(i,j)+"\t"; text+=d_table->text(i,right)+"\n"; } } // Copy text into the clipboard QApplication::clipboard()->setData(new QTextDrag(text,d_table,0)); }
virtual QwtText trackerTextF( const QPointF &pos ) const { QwtText text; const QPolygon points = selection(); if ( !points.isEmpty() ) { QString num; num.setNum( QLineF( pos, invTransform( points[0] ) ).length() ); QColor bg( Qt::green ); bg.setAlpha( 200 ); text.setBackgroundBrush( QBrush( bg ) ); text.setText( num ); } return text; }
TEST_F(FrameSelectionTest, SetInvalidSelection) { // Create a new document without frame by using DOMImplementation. DocumentInit dummy; RefPtrWillBeRawPtr<Document> documentWithoutFrame = Document::create(); RefPtrWillBeRawPtr<Element> body = documentWithoutFrame->createElement(HTMLNames::bodyTag, false); documentWithoutFrame->appendChild(body); RefPtrWillBeRawPtr<Text> anotherText = documentWithoutFrame->createTextNode("Hello, another world"); body->appendChild(anotherText); // Create a new VisibleSelection for the new document without frame and // update FrameSelection with the selection. VisibleSelection invalidSelection; invalidSelection.setWithoutValidation(Position(anotherText, 0), Position(anotherText, 5)); setSelection(invalidSelection); EXPECT_TRUE(selection().isNone()); }
char * crossover(char **population, double p_crossover) { //selection int x = 0, y = 0; //x,y store the index of two selected parents selection(population, &x, &y); //printf("selected parents index: %d %d\n",x, y); char *child = (char *) malloc(LENGTH * sizeof(char)); int crossover_point = p_crossover * LENGTH; int gene; for (gene = 0; gene < LENGTH; gene++) { if (gene < crossover_point) child[gene] = population[x][gene]; else child[gene] = population[y][gene]; } // printf("parents : %s %s\n", population[x], population[y]); return child; }
void worksheet::active_cell(const cell_reference &ref) { if (!has_view()) { d_->views_.push_back(sheet_view()); } auto &primary_view = d_->views_.front(); if (!primary_view.has_selections()) { primary_view.add_selection(selection(pane_corner::bottom_right, ref)); } else { primary_view.selection(0).active_cell(ref); } }
int main (int argc, char **argv) { int i, flag; flag = 0; initiate(); // 产生初始化群体 evaluation(0); // 对初始化种群进行评估、排序 for (i = 0; i < MAXloop; i++) { // 进入进化循环,当循环次数超过MAXloop所规定的值时终止循环,flag值保持为0 cross(); // 进行交叉操作 evaluation(1); // 对子种群进行评估、排序 selection(); // 从父、子种群中选择最优的NUM个作为新的父种群 if (record() == 1) { // 如果满足终止规则1时将flag置1,停止循环 flag = 1; break; } mutation(); // 进行变异操作 } showresult(flag); // 按flag值显示寻优结果 return 0; }
void view_file_cmd (void) { char *filename; vfs_path_t *vpath; filename = input_expand_dialog (_("View file"), _("Filename:"), MC_HISTORY_FM_VIEW_FILE, selection (current_panel)->fname, INPUT_COMPLETE_FILENAMES); if (filename == NULL) return; vpath = vfs_path_from_str (filename); g_free (filename); view_file (vpath, FALSE, use_internal_view != 0); vfs_path_free (vpath); }
void Cena::mousePressEvent( QMouseEvent* event ) { if (smgr) { selection(); mouseXi = device->getCursorControl()->getPosition().X; mouseYi = device->getCursorControl()->getPosition().Y; if(selectedSceneNode){ xi = selectedSceneNode->getPosition().X; yi = selectedSceneNode->getPosition().Y; zi = selectedSceneNode->getPosition().Z; } sendMouseEventToIrrlicht(event, true); drawIrrlichtScene(); } event->ignore(); }
int main() { char finame[64],foname[64]={0}; int chal,chud; FILE *fi,*fo; printf("入力ファイル名を入力してください.\n"); scanf("%s",finame); fi=fileOpen(finame,"r"); strncpy(foname,finame,strlen(finame)-strlen(strrchr(finame,'.'))); strcat(foname,".out"); fo=fileOpen(foname,"w"); printf("実行するアルゴリズムを選択してください.\n|バブルソート---1 選択ソート---2 挿入ソート---3|"); scanf("%d",&chal); printf("並べ替え方法を選択してください.\n|昇順---1 降順---2|"); scanf("%d",&chud); switch(chal){ case 1: bubble(chud,fi,fo); break; case 2: selection(chud,fi,fo); break; case 3: insertion(chud,fi,fo); break; default: printf("おかしな値を入力しないでください.\n"); } fclose(fi); fclose(fo); return 0; }
extern void swGPUParamSearch(Chain* rowChainL, Chain* columnChainL, SWPrefs* swPrefsL) { SWResult* swResult = swDataGetResult(swSolveGPU(rowChainL, columnChainL, swPrefsL), 0); rowChain = rowChainL; columnChain = columnChainL; swPrefs = swPrefsL; columns = chainGetLength(columnChainL); expectedResult = swResultGetScore(swResult); srand(time(NULL)); Cromosome child; initPopulation(); evaluatePopulation(); int generationIdx; int childIdx; for (generationIdx = 0; generationIdx < GENERATION_NMR; ++generationIdx) { sortCromosomes(population, 0, POPULATION_NMR - 1); printf(".............................................\n"); printf("Generation: %d\n", generationIdx); for (childIdx = 0; childIdx < CHILD_NMR; ++childIdx) { child = crossover(selection()); mutation(&child); children[childIdx] = child; } evaluateChildren(); for (childIdx = 0; childIdx < CHILD_NMR; ++childIdx) { population[POPULATION_NMR - childIdx - 1] = children[childIdx]; } } }
// Subclassed handle() for keyboard searching int EDE_Browser::handle(int e) { if (e==FL_FOCUS) { fprintf(stderr, "EB::focus\n"); } if (e==FL_KEYBOARD && Fl::event_state()==0) { // when user presses a key, jump to row starting with that character int k=Fl::event_key(); if ((k>='a'&&k<='z') || (k>='A'&&k<='Z') || (k>='0'&&k<='9')) { if (k>='A'&&k<='Z') k+=('a'-'A'); int ku = k - ('a'-'A'); //upper case int p=lineno(selection()); for (int i=1; i<=size(); i++) { int mi = (i+p-1)%size() + 1; // search from currently selected one if (text(mi)[0]==k || text(mi)[0]==ku) { // select(line,0) just moves focus to line without selecting // if line was already selected, it won't be anymore select(mi,selected(mi)); middleline(mi); //break; return 1; // menu will get triggered on key press :( } } } // Attempt to fix erratic behavior on enter key // Fl_Browser seems to do the following on enter key: // - when item is both selected and focused, callback isn't called at all (even FL_WHEN_ENTER_KEY_ALWAYS) // - when no item is selected, callback is called 2 times on focused item // - when one item is selected and other is focused, callback is first called on selected then on // focused item, then the focused becomes selected // This partial fix at least ensures that callback is always called. Callback function should // deal with being called many times repeatedly. if ((when() & FL_WHEN_ENTER_KEY_ALWAYS) && k == FL_Enter) { // if (changed()!=0) { //fprintf(stderr,"do_callback()\n"); do_callback(); // } } if (k == FL_Tab) { fprintf (stderr, "TAB\n"); // Fl_Icon_Browser::handle(FL_UNFOCUS); return 1; } } return Fl_Icon_Browser::handle(e); }
//_______________________________________________________ void ExceptionListWidget::up( void ) { InternalSettingsList selection( model().get( m_ui.exceptionListView->selectionModel()->selectedRows() ) ); if( selection.empty() ) { return; } // retrieve selected indexes in list and store in model QModelIndexList selectedIndices( m_ui.exceptionListView->selectionModel()->selectedRows() ); InternalSettingsList selectedExceptions( model().get( selectedIndices ) ); InternalSettingsList currentException( model().get() ); InternalSettingsList newExceptions; for( InternalSettingsList::const_iterator iter = currentException.constBegin(); iter != currentException.constEnd(); ++iter ) { // check if new list is not empty, current index is selected and last index is not. // if yes, move. if( !( newExceptions.empty() || selectedIndices.indexOf( model().index( *iter ) ) == -1 || selectedIndices.indexOf( model().index( newExceptions.back() ) ) != -1 ) ) { InternalSettingsPtr last( newExceptions.back() ); newExceptions.removeLast(); newExceptions.append( *iter ); newExceptions.append( last ); } else newExceptions.append( *iter ); } model().set( newExceptions ); // restore selection m_ui.exceptionListView->selectionModel()->select( model().index( selectedExceptions.front() ), QItemSelectionModel::Clear|QItemSelectionModel::Select|QItemSelectionModel::Rows ); for( InternalSettingsList::const_iterator iter = selectedExceptions.constBegin(); iter != selectedExceptions.constEnd(); ++iter ) { m_ui.exceptionListView->selectionModel()->select( model().index( *iter ), QItemSelectionModel::Select|QItemSelectionModel::Rows ); } setChanged( true ); return; }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QStandardItemModel *model = new QStandardItemModel(7, 4, this); for (int row = 0; row < 7; ++row) { for (int column = 0; column < 4; ++column) { QStandardItem *item = new QStandardItem(QString("%1") .arg(row * 4 + column)); model->setItem(row, column, item); } } tableView = new QTableView; tableView->setModel(model); setCentralWidget(tableView); // 获取视图的项目选择模型 QItemSelectionModel *selectionModel = tableView->selectionModel(); // 定义左上角和右下角的索引,然后使用这两个索引创建选择 QModelIndex topLeft; QModelIndex bottomRight; topLeft = model->index(1, 1, QModelIndex()); bottomRight = model->index(5, 2, QModelIndex()); QItemSelection selection(topLeft, bottomRight); // 使用指定的选择模式来选择项目 selectionModel->select(selection, QItemSelectionModel::Select); ui->mainToolBar->addAction(tr("当前项目"), this, SLOT(getCurrentItemData())); ui->mainToolBar->addAction(tr("切换选择"), this, SLOT(toggleSelection())); connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(updateSelection(QItemSelection,QItemSelection))); connect(selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(changeCurrent(QModelIndex,QModelIndex))); // 多个视图共享选择 tableView2 = new QTableView; tableView2->setWindowTitle("tableView2"); tableView2->resize(400, 300); tableView2->setModel(model); tableView2->setSelectionModel(selectionModel); tableView2->show(); }
/*! * updates the selection model * The selection model will signal the view. */ void UsbUiSettingModel::updateSelectionModel(int newPersonality) { myDebug() << ">>> UsbUiSettingModel::updateSelectionModel value=" << newPersonality; mCurrentMode = newPersonality; mSelectionModel->clear(); int row = mPersonalityIds.indexOf(newPersonality); myDebug() << ">>> UsbUiSettingModel::updateSelectionModel row=" << row; // in case of the hidden personality , the selection model is left empty if ( row >= 0 ) { //set selection model for the new selection QModelIndex selectionIndex = index(row, 0, QModelIndex()); QItemSelection selection(selectionIndex, selectionIndex); mSelectionModel->select(selection, QItemSelectionModel::Select); } myDebug() << "<<< UsbUiSettingModel::updateSelectionModel"; }
NS_IMETHODIMP IMEContentObserver::SelectionChangeEvent::Run() { if (!CanNotifyIME()) { return NS_OK; } if (!IsSafeToNotifyIME()) { mIMEContentObserver->PostSelectionChangeNotification( mCausedByComposition, mCausedBySelectionEvent); return NS_OK; } // XXX Cannot we cache some information for reducing the cost to compute // selection offset and writing mode? WidgetQueryContentEvent selection(true, NS_QUERY_SELECTED_TEXT, mIMEContentObserver->mWidget); ContentEventHandler handler(mIMEContentObserver->GetPresContext()); handler.OnQuerySelectedText(&selection); if (NS_WARN_IF(!selection.mSucceeded)) { return NS_OK; } // The state may be changed since querying content causes flushing layout. if (!CanNotifyIME()) { return NS_OK; } IMENotification notification(NOTIFY_IME_OF_SELECTION_CHANGE); notification.mSelectionChangeData.mOffset = selection.mReply.mOffset; notification.mSelectionChangeData.mLength = selection.mReply.mString.Length(); notification.mSelectionChangeData.SetWritingMode( selection.GetWritingMode()); notification.mSelectionChangeData.mReversed = selection.mReply.mReversed; notification.mSelectionChangeData.mCausedByComposition = mCausedByComposition; notification.mSelectionChangeData.mCausedBySelectionEvent = mCausedBySelectionEvent; IMEStateManager::NotifyIME(notification, mIMEContentObserver->mWidget); return NS_OK; }
void OnMenuFindSel(WindowInfo *win, TextSearchDirection direction) { if (!win->IsDocLoaded() || !NeedsFindUI(win) || win->IsChm()) return; if (!win->selectionOnPage || 0 == win->dm->textSelection->result.len) return; ScopedMem<WCHAR> selection(win->dm->textSelection->ExtractText(L" ")); str::NormalizeWS(selection); if (str::IsEmpty(selection.Get())) return; win::SetText(win->hwndFindBox, selection); AbortFinding(win); // cancel FAYT Edit_SetModify(win->hwndFindBox, FALSE); win->dm->textSearch->SetLastResult(win->dm->textSelection); FindTextOnThread(win, direction); }
void PlaylistView::RemoveSelected() { int rows_removed = 0; QItemSelection selection(selectionModel()->selection()); if (selection.isEmpty()) { return; } // Sort the selection so we remove the items at the *bottom* first, ensuring // we don't have to mess around with changing row numbers qSort(selection.begin(), selection.end(), CompareSelectionRanges); // Store the last selected row, which is the first in the list int last_row = selection.first().bottom(); foreach (const QItemSelectionRange& range, selection) { rows_removed += range.height(); model()->removeRows(range.top(), range.height(), range.parent()); }
void main() { int data[] = {10,9,8,7,6,5,4,2,3,1}; int i = 0; system("cls"); printf("Origianl Data : " ); for(i=0;i<10;i++) printf("%d ",data[i]); selection(data,10); printf("\nSorted Data : ") ; for(i=0;i<10;i++) printf("%d ",data[i]); getch(); }
void Nmr::on_shieldingsTable_itemSelectionChanged() { QList<QTableWidgetItem*> selection(m_ui->shieldingsTable->selectedItems()); //qDebug() << "on_shieldingsTable_itemSelectionChanged called with slection" // << selection.size(); if (selection.isEmpty()) return; int row(selection.last()->row()); // First find the name of the graph QString name; QMap<int, QList<int> >::iterator iter; for (iter = m_graphToRows.begin(); iter != m_graphToRows.end(); ++iter) { if (iter.value().contains(row)) { //qDebug() << "row selected" << row << "found in" << iter.key(); //qDebug() << "Selected rows: " << iter.value(); selectAtoms(iter.value()); name = QString::number(iter.key()); break; } } if (!m_ui->impulseButton->isChecked()) return; if (name.isEmpty()) return; // now find the graph int index; for (index = 0; index < m_plot->graphCount(); ++index) { if (m_plot->graph(index)->name() == name) break; } if (index == m_plot->graphCount()) return; QCPGraph* graph(m_plot->graph(index)); if (graph && graph->selected()) return; QList<QCPGraph*> selectedGraphs(m_plot->selectedGraphs()); QList<QCPGraph*>::iterator it; for (it = selectedGraphs.begin(); it != selectedGraphs.end(); ++it) { (*it)->setSelected(false); } if (graph) graph->setSelected(true); m_plot->replot(); }
Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); //menu QPushButton *quit = new QPushButton(tr("Quit")); quit->setFont(QFont("Times", 18, QFont::Bold)); connect(quit, SIGNAL(clicked()), qApp, SLOT(quit())); ui->menu->addWidget(quit, 0, 0); //scene tapis scene = new QGraphicsScene(0,0,700,450); connect(scene, SIGNAL(selectionChanged()), this, SLOT(selection())); ui->graphicsView->setScene( scene ); ui->graphicsView->setDragMode(QGraphicsView::RubberBandDrag); //menu jeu playgame QPushButton *Cancel = new QPushButton(tr("Cancel")); Cancel->setFont(QFont("Times", 18, QFont::Bold)); connect(Cancel, SIGNAL(clicked()), this, SLOT(recup_cards())); ui->playgame->addWidget(Cancel, 0, 0); LCDRange *mise = new LCDRange; ui->playgame->addWidget(mise, 0, 1); QPushButton *OK = new QPushButton(tr("OK")); OK->setFont(QFont("Times", 18, QFont::Bold)); connect(OK, SIGNAL(clicked()), this, SLOT(change_cards())); ui->playgame->addWidget(OK, 0, 2); // compte du joueur initJoueur(&joueur); //lancement createHelp(); initPaquet(&jeu); this->createCards(); creerJeu(&jeu); /* cree un jeu de 52 carte (complet) */ melangerPaquet(&jeu); restartGame(); }
void main(void) { int * intArrays[COPIES], i, arraySize, value; clrscr(); printf("This program sorts and searches integer values!\n"); printf("please give me number of values you wish to deal with: "); scanf("%d", &arraySize); for(i = 0;i < COPIES; i++) intArrays[i] = (int *) malloc(sizeof(int) * arraySize); readValues(intArrays, arraySize); printf("Enter number to search for? (linear search): "); scanf("%d", &value); if (linearSearch(intArrays[0], arraySize, value) != -1) printf("Found !\n"); else printf("Not Found!\n"); getch(); printValues(intArrays, arraySize); printf("\nSorting Array 1 using bubble....\n"); bubble(intArrays[0], arraySize); printValues(intArrays, arraySize); printf("\nSorting Array 2 using selection....\n"); selection(intArrays[1], arraySize); printValues(intArrays, arraySize); printf("\nSorting Array 3 using insertion....\n"); insertion(intArrays[2], arraySize); printValues(intArrays, arraySize); printf("Enter number to search for? (binary search): "); scanf("%d", &value); if (linearSearch(intArrays[0], arraySize, value) != -1) printf("Found !\n"); else printf("Not Found!\n"); getch(); }
void PlaylistView::RemoveSelected() { int rows_removed = 0; QItemSelection selection(selectionModel()->selection()); if (selection.isEmpty()) { return; } // Store the last selected row, which is the last in the list int last_row = selection.last().top(); // Sort the selection so we remove the items at the *bottom* first, ensuring // we don't have to mess around with changing row numbers qSort(selection.begin(), selection.end(), CompareSelectionRanges); for (const QItemSelectionRange& range : selection) { if (range.top() < last_row) rows_removed += range.height(); model()->removeRows(range.top(), range.height(), range.parent()); } int new_row = last_row - rows_removed; // Index of the first column for the row to select QModelIndex new_index = model()->index(new_row, 0); // Select the new current item, we want always the item after the last // selected if (new_index.isValid()) { // Workaround to update keyboard selected row, if it's not the first row // (this also triggers selection) if (new_row != 0) keyPressEvent( new QKeyEvent(QEvent::KeyPress, Qt::Key_Down, Qt::NoModifier)); // Update visual selection with the entire row selectionModel()->select(new_index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); } else { // We're removing the last item, select the new last row selectionModel()->select( model()->index(model()->rowCount() - 1, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); } }