QTableWidget cast loses selectedItems - qt

I am adding QTableWidgets to a layout (called tableArea). I have a function that I want to be able to go through all the selected items in all tables I have added to my layout:
for (int i=0; i <ui->tableArea->count(); i++)
{
QTableWidget *tableI = (QTableWidget*)ui->tableArea->itemAt(i)->widget();
int rowCount = tableI->rowCount(); // just to test if correct info
QList<QTableWidgetItem*> list = tableI->selectedItems(); // This is empty!!
}
The function iterates through correct tables, and it even knows the right row count for each table, but it doesn't seem to know which items are selected in the table. When I select items, this function doesn't seem to recognize that there is something selected. I imagine this has to do with the cast. Any idea? Thanks in advance!

Related

Xamarin grid, column and row amounts

Hi im relatively new to c# code and i was wondering if there is any way to get the amount of columns and rows in a grid and store that amount in a variable
Something like:
var columnamount = grid.columnamount;
But i could not find anything that works
Thanks
You can use the following code to get a count of the columns and rows directly via the ColumnDefinitions and RowDefinitions properties. No need to enumerate the children of the grid because you may not have views in every column/row.
var columnCount = grid.ColumnDefintions.Count;
var rowCount = grid.RowDefinitions.Count;
For reference the documentation.
You might be able to do it this way, purely based on what I see in the docs:
var countColumns = grid.Children.Where( c => c.Column).Max();
var countRows = grid.Children.Where( c => c.Row).Max();
But I'm not sure if you can access Row anf Column properties on the child element.
This is not the best way to check, I guess, but it's working (same thing for columns):
EDIT: nope, for columns it doesn't work
int GetRowsCount(Grid grid)
{
var item = grid.Children.FirstOrDefault();
return item != null ? Grid.GetRow(item) + 1 : 0;
}

QListView with QStandardItemModel does not show selection highlight through code

I have a QListView that is populated with either a QStandardItemModel or a QStringListModel (based on simplicity of contents... number of columns).
On load, or switching between widgets, I search for the item that should be selected, and try to highlight it.
if (first)
{
m_myListView.setModel(m_standardItemModel);
QList<QStandardItem*> lst = m_standardItemModel->findItems(m_value1, Qt::MatchExactly, 1);
if(!lst.isEmpty())
{
QModelIndex index = lst.at(0)->index();
qDebug() << index.row(); // tells me correct row
//m_myListView.setCurrentIndex(index); // no change if I use
m_myListView.selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
m_myListView.scrollTo(index);
}
}
else
{
m_myListView.setModel(m_stringListModel);
int i = m_stringListModel->stringList().indexOf(m_value2);
if (i >= 0)
{
QModelIndex index = m_stringListModel->index(i);
m_myListView.selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
m_myListView.scrollTo(index);
}
}
The m_stringListModel version correctly highlights (and scrolls to item).
The m_standardItemModel version does not highlight row, and does not scroll to item. But in the uses afterwards, it correctly provides the data for selected index:
QModelIndexList indexList = m_myListView.selectionModel()->selectedIndexes();
if (!indexList.isEmpty())
{
QModelIndex index = indexList.first();
if (index.isValid())
{
row = index.row();
data1 = m_standardItemModel->index(row, 1).data().toString();
...
So... it seems that the selection works, but if it does, why do I not see a highlight ? (and the scrollTo() )
Note - the code is pretty giant but I verified for the possibility of reloading the model and possibly losing the selection - and besides, the QStringListModel version works correctly.
Is that a typical behavior of QStandardItemModel, or is there something I must do, like setting a BackgroundRole type data ?
How can I highlight the selection of the list view with the QStandardItemModel applied ?
I see your code, probably you want to select the first element of your model? Let's try:
void MyClass::selectFirstElement() {
const QModelIndex firsIndex = _myModel->index(0,0);
if (index.isValid())
ui->listView->setCurrentIndex(firstIndex);
ui->listView->scrollTo(firstIndex);
}
}
Could you share the m_standardItemModel implementation? Also configure your list correctly:
ui->listView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->listView->setSelectionBehavior(QAbstractItemView::SelectRows); // Or Columns
Check if your QStandarItem has the selection flag enable. See http://doc.qt.io/qt-4.8/qt.html#ItemFlag-enum for more info.
Finally, you could ensure that the index is stored in the correct model by getting the index in the same row & column directly from the model, something like this:
QModelIndex index = lst.at(0)->index();
index = _model->index(index.row(), index.column());
Sorry, for my poor english :S
Because the item found is different than the display item, the list view is unable to select it...
2 solutions: either create a different QModelIndex from the one found, pointing to the display column, or select an entire row containing the desired index:
m_myListView.selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);

Hide columns in a GridView when new columns are added

Have landed into a scenario.
I have a gridview with 22 static columns (few are BoundFields, few are TemplateFields).
We have a scenario in our project that we need to order the GridView according to the columns selected. The order of the columns selected is provided from the UI.
For ex: We have Doc1 to Doc23 as the columns.
Now, from the functionality provided in the UI, I am passing some 4 columns say Doc2,Doc4,Doc5,Doc7.
Now I want that only these 4 columns should be present in my grid as a final output.
Have tried some code, but it doesn't seem to work.
Below is my code:
public int GridColumnOrdering(string columnList)
{
string[] test = columnList.Split(';');
var docCatColumn = gridResultSet.Columns[0];
var docTypeColumn = gridResultSet.Columns[1];
int columnCount = 0;
int testCount = 0;
for (int i = 0; i < test.Count(); i++)
{
if (test[i] == "Doc2")
{
gridResultSet.Columns.Insert(i , docCatColumn);
columnCount++;
}
if (test[i] == "Doc3")
{
gridResultSet.Columns.Insert(i , docTypeColumn);
columnCount++;
}
}
gridResultSet.Columns[2].Visible = false;
gridResultSet.Columns[3].Visible = false;
}
columnList is a parameter passed which has values such as Doc2;Doc3.
My idea is that I get the static columns which resemble the column gotten from the UI, change its position to the very next position, and then hide that static column. In this way, we actually have 2 columns by the same name, but I am trying to hide the static one and display the dynamic one.
I know it sounds weird and hectic, but this is what came to my mind.
Now the problem is that if I try to change the visibility of the static column, the visibility of the dynamic one also changes.
Can experts help on this issue or point out to some easy method in this regards??
Regards
Anurag

XtraGrid set selection on match datamember

We want to set the selection on a XtraGrid based on a List collection from the same type as the datamember of an XtraGrid.
The way we do it now is to iterate the gridview rows.
private void SetSelectedRowsInternal(IList<StrongType> collecshung)
{
grdvSomeGrid.ClearSelection();
grdvSomeGrid.BeginSelection();
for (int i = 0;i < grdvSomeGrid.RowCount;i++)
{
StrongType _strongTyped = ((StrongType)grdvSomeGrid.GetRow(i));
if (collecshung.Where(x => x.Id == _strongTyped.Id).Count() == 1)
grdvSomeGrid.SelectRow(i);
}
grdvSomeGrid.EndSelection();
}
Is there a better way to do this?
It depends on how you fill your grid ... You can directly iterate on the BindingList for instance (using LINQ). But if you find that it is taking more time than needed, then it should be because LINQ functions can be hit more than 1 million time even for a small amount of data.
I recommend you to use a dictionary instead of a LINQed collection.

Regarding to retrieve values inside the array

Hi
I am creating online quiz in asp.net c#. For that i have one form that displays testlist in dropdownlist & start button. After clicking 2nd form appears, 2nd form shows one label for question, radiobuttonlist for answers ,next & checkbox for review. I am creating array of random question ids in start button click event of the 1stform. when i click next button in 2nd form then next random question appears, i want array of questions those are checked for review. I used code for arrays of values ( eg.10101) 1 for true & 0 for false as follows but i want array of that question ids those are checked:
int[] a = (int[])Session["values"];//this is array of random question ids created in 1st form
int g;
if (chkmark.Checked == true)
{
g = 1;
}
else
{
g = 0;
}
int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
int[] temp1 = (int[])Session["arrofchk"];
int k, no;
if (temp1 == null)
no = 0;
else
no = temp.Length;
for (k = 0; k < no; k++)
{
chkarray[k] = temp1[k];
}
chkarray[j] = g;
Personally, i would use a Dictionary<int, bool> for this.
In the key of the dictionary, you can store the random Question ID, in the value of the pair, you can store the checked item state. It might take you more work now to refactor it, but I believe it will save you a lot of time in the end when you want to do more actions on your quiz items.
Using a dictionary - or at least a well chosen collection, I think it will be easier to get the right data back.
For your example, it can work only if the positions of both arrays are the same.
Dictionary<int, bool> quizAnswers = new Dictionary<int, bool>(); // <questionID, checked>
// Fill dictionary with questions and answers
for(int i=0;i<a.length;i++)
{
if(temp1.length > i) // Make sure we don't get an IndexOutOfBoundsException
{
quizAnswers.Add(a[i], temp1[i] == 1);
}
}
// Get Answered question in array ( LINQ )
int[] checkedAnswers = (from KeyValuePair<int, bool> pair in quizAnswers
where pair.Value == true
select pair.Key).ToArray<int>();
The reason I am using a Dictionary here, is because I personally think it's neater than having two separate arrays.
I believe you should implement a Dictionary in your quiz, in stead of those arrays. What if the array indexes don't match, or you want to dynamically add a question to a fixed size array, etc..
It's something to take into consideration. Hope I could help you out.

Resources