How can read selected items from QTableWidget?
Thanks
int QTableWidget::currentRow() const
Returns the row of the current item.
int QTableWidget::currentColumn() const
Returns the column of the current item.
Some options (there are also others out there too):
# selectedRanges(), would give you the second cell from each selected row, for example:
indexes = []
for selectionRange in myTable.selectedRanges():
indexes.extend(range(selectionRange.topRow(), selectionRange.bottomRow()+1))
print "indexes", indexes # indexes is a list like [0, 2] of selected rows
for i in indexes:
print "specific item", myTable.item(i, 1).text()
results.append( str(myTable.item(i, 1).text()) )
# selectedItems()
for item in myTable.selectedItems():
print "selectedItems", item.text()
# selectedIndexes()
for item in myTable.selectedIndexes():
print "selectedIndexes", item.row(), item.column()
Use the selectedItems function to retrieve the selected items or the selectedIndexes to get all selected cells including empty ones.
the best way to access the items in a qtablewidget is using the function
QList QTableWidget::selectedRanges () const
Related
I am trying to automate a PyQt based application that uses a QListView in icon mode using Squish
Inorder to select a specific item in the view, i need to first identify the text of the item. I am using the below code to do the same
targetList = waitForObject("{name='someListView' type='QListView'}")
object.children(targetList)[11].model().data(object.children(targetList)[11]).toString()
Here object.children(targetList)[11] is of type QModelIndex
But the above code always returns an empty string.
Is there any other way to retrieve the text data
I would rather use QListView API only. So, in case of valid targetList object, i.e. it's found by waitForObject function, I would write:
targetList = waitForObject("{name='someListView' type='QListView'}")
model = targetList.model()
col = targetList.modelColumn
idx = model.index(11, col)
itemString = idx.data().toString()
Here is an example:
def main():
# Use itemviews example included in Squish:
startApplication("itemviews")
# Configure QListView to use IconMode as
# mentioned by original poster:
obj = waitForObject("{occurrence='2' type='QListView' unnamed='1' visible='1'}")
obj.setViewMode(QListView.IconMode)
# Get desired item via object.children();
# this yields a "wrapped" QModelIndex which
# features a property "text" which contains
# the desired text:
it = object.children(obj)[4]
test.log("item text: %s" % it.text)
I am trying to make a calendar with CheckButton groups in a column. The problem is that I can't figure out which button is selected.
group1 = CheckboxButtonGroup(
labels=["05", "06","07", "08","09"], height=10)
group2 = CheckboxButtonGroup(
labels=["12", "13","14", "15","16"] , height=10)
group3 = CheckboxButtonGroup(
labels=["19", "20","21", "23","24"] , height=10)
calendar = column(group1, group2, group3)
I want a function as follows:
def returnDaySelected(calendar):
return SelectedDay
I understand that I have three groups, and I have to make a few ifs to get the group I want. But still. I can't find the groups inside the column.
I tried printing dir(calendar) and dir(calendar.children[0]) to see what is inside the column. But I could not find an attribute that would give me back the groups, let alone the selected button.
Any ideas in how to return the selected button? (Or all of the selected buttons)
Try calendar.children[0].children[0].active returns a list of the buttons pressed, e.g., if the 2nd and 3rd buttons are pressed it will return [1,2] (counting from 0).
The column.children[0] returns just the WidgetBox. Another call is required to access its children.
def returnDaysSelected(calendar):
selectedDays = []
for iGroup in calendar.children[0].children:
active = iGroup.active
for iDay in active:
selectedDays.append(iGroup.labels[iDay])
return selectedDays
I have a qtablewidget with some rows. I need to sort these row randomly.
What is the best way to do this ? I have no idea except remove and add all row randomly ...
"I assume you are looking for some custom sort. Not column header click sort"
I have a way to do it. may be much more efficient way will be there.
get the "QList" of "QTableWidgetItem" using below function.
QList<QTableWidgetItem *> findItems(const QString & text, Qt::MatchFlags flags) const
Then sort your list as shown below with your condiion
bool sortFun(const QTableWidgetItem* v1, const QTableWidgetItem* v2)
{
return //your sor criteria;
}
int doComparison()
{
QList<QTableWidgetItem *> fieldsList;
// Add items to fieldsList.
qSort(fieldsList.begin(), fieldsList.end(), sortFun);
}
Not clear your "QTableWidget".
Then re assign your sorted list of "QTableWidgetItems" to QTableWidget
Finally I have done something different.
What I need to do:
- random the rows of my table
- I have a column with a "Time" and I initialize it with 15:00 for the first row and then add 1 minute for each row.
The solution I used:
- create a qlist with my times (15:00, 15:01, 15:02 ...)
- randomize the qlist (15:01, 15:03, ....)
- assign the qlist's items to the column "Time" of my table
- order my table with the column "Time" with the sort column method.
It is a standard QTableWidget
All cells are QTableWidgetItem.
All cells are editable/selectable
Question: How can I modify all the cells I have selected?
Possible way is to use the dialog open. So the idea is like this :
Select the items
Make a button or something to open input dialog.
Apply the value of input dialog to all selected items.
I was facing a similar problem a couple years ago and I solved it like this:
I have inherited my own view and I have reimplemented methods commitData() and mouseReleaseEvent().
commitData takes all selected indices from the selection model and calls QAbstractItemModel::setData() for all of them. Data are taken from the editor like this:
QByteArray n = editor->metaObject()->userProperty().name();
if (n.isEmpty())
n = delegate->itemEditorFactory()->valuePropertyName(model()->data(index, Qt::EditRole).userType());
if (!n.isEmpty())
{
QVariant data = editor->property(n);
for (const QModelIndex & idx : selectedIndices)
{
model()->setData(idx, data);
}
}
mouseReleaseEvent() performs three steps:
Get a current selection from the selection model.
Call original event handler (QTableWidget::mouseReleaseEvent())
Restore selection: QItemSelectionModel::select()
I have QTreeView and I setSortEnable = true for it, and all of column show sort indicator, but now I want last column do not show sort indicator, just last column.
Have any idea or solution for my issue..:(
please help
Thanks
QHeaderView always draws the sorting indicator on a column when data is sorted by this column (if setSortIndicatorShown is true).
That is why it look like the only way to prohibit drawing of the indicator is to prohibit sorting of the column by left-click.
To prohibit sorting by a certain column you need:
1. create a new class inherited from QHeaderView (or use an event filter)
2. reimplement mouseReleaseEvent and mousePressEvent
3. use logicalIndexAt to indicate that user clicked on the column
4. call setSectionsClickable(false) before calling the base method and setSectionsClickable(true) after it.
Example:
void HeaderView::mouseReleaseEvent(QMouseEvent* e)
{
const int index = logicalIndexAt(e->pos());
if (index == 3) setSectionsClickable(false);
QHeaderView::mouseReleaseEvent(e);
setSectionsClickable(true);
}
Do the same for mousePressEvent.
thus you will prohibit sorting of a certain column
In my case, I've three columns and it was necessary to hide the sort indicator of the second column.
Because of I had custom rules of sorting, just got QHeaderView::sectionClicked event with OnHeaderClicked(int column) slot, and did this:
switch (column)
{
case 0:
// Custom sorting operations
break;
case 1:
tree_widget_->sortByColumn(-1);
break;
case 2:
// Custom sorting operations
break;
}