I have a QTable Widget of one column populated with several rows, and I would like to be able to drag and drop so i can re order them.
I am able to do setDragDropMode with Internal Move, but when i move cell (0,1) to (0,3)
the (0,3) get the text correctly, but cell (0,1) is now empty. I would like to swap the text of the cell when I drop it.
class myList(QtGui.QTableWidget):
def __init__(self,parent):
super(myList,self).__init__(parent)
# self.setAcceptDrops(True)
self.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
You can override the dropEvent callback to alter the default action. Here is a first version that writes the value in both cells.
class TableSwitcher(QtGui.QTableWidget):
def dropEvent(self, dropEvent):
item_src = self.selectedItems()[0]
item_dest = self.itemAt(dropEvent.pos())
src_value = item_src.text()
item_src.setText(item_dest.text())
item_dest.setText(src_value)
You can also let Qt performs the default behavior (move the dragged QTableWidgetItem, and delete the one you drop on) through super call , here you face the challenge that the default action will alter the state of widgets.
class TableSwitcher(QtGui.QTableWidget):
def dropEvent(self, dropEvent):
item_src = self.selectedItems()[0]
item_dest = self.itemAt(dropEvent.pos())
src_row = item_src.row()
src_col = item_src.column()
dest_value = item_dest.text()
super(TableSwitcher,self).dropEvent(dropEvent)
self.setItem(src_row,src_col, QtGui.QTableWidgetItem(dest_value))
Here is an example code using this class.
app = QtGui.QApplication(sys.argv)
table = TableSwitcher()
n = 5
table.setRowCount(n)
table.setColumnCount(1)
table.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
for i in range(n):
table.setItem(i,0,QtGui.QTableWidgetItem(str(i)))
table.show()
app.exec_()
Related
Using the answer provided by aka863 here: How to split merged Excel cells with Python?
I can unmerge, fill values and copy the styling. My questions is how to make the value assigning/filling process configurable.
I want the user to be able to choose whether the values will be filled vertically/horizontally.
I have tried changing the last loop where we assign the top_left_cell_values to unmerged cells. However I couldn't find a way to make it horizontal/vertical configurable. (I'm planning to use radio buttons and tkinter for this)
Its certainly possible to have the code de-merge cells and fill cells in whichever direction, vertically or horizontally regardless of which way the merge was originally. Or not fill at all, so only the top left cell retains the 'value' of the previously merged cells, which is default on unmerge.
Changing the direction of the fill requires some change and re-calculation on the max row and column values in the iter_rows loop, but is simple enough.
However it seems in your last comment you just want to give the user the option to fill or not fill on horizontal merges. In that case you just need to ask the question, and then run the iter_rows loop only if the response is yes.
The code sample below is based on the answer referenced question.
I'm assuming only single line horizontal merges since you dont mention what if anything should be done with vertical merges in the comment.
The code does initially check and indicate the merge direction either vertically or horizontally so it can be included take some action if a merge is vertical.
On code run after displaying the range and direction of the merge, the question is asked to fill, yes or no. If yes the cells are de-merged and all cells filled with the top left cell value using the iter_rows loop. If answer no then the cells are just de-merged.
from openpyxl import load_workbook
from openpyxl.utils.cell import range_boundaries
wb = load_workbook(filename='foo.xlsx')
st = wb['Sheet1']
mcr_coord_list = [mcr.coord for mcr in st.merged_cells.ranges]
direction_dict = {'v': 'vertical', 'h': 'horizontal'}
for mcr in mcr_coord_list:
print('---------------------------------------------------\n')
merge_direction = ''
min_col, min_row, max_col, max_row = range_boundaries(mcr)
top_left_cell_value = st.cell(row=min_row, column=min_col).value
if min_col == max_col:
merge_direction = 'v'
elif min_row == max_row:
merge_direction = 'h'
print(f"The cell range {mcr} is merged {direction_dict[merge_direction]}ly with the data '{top_left_cell_value}'")
while True:
demerge_fill = input('Do you want the de-merge to fill all cells(y|n)? ')
if demerge_fill.lower() in ["y", "n"]:
break
else:
print('Invalid response')
st.unmerge_cells(mcr)
if demerge_fill == 'y':
for row in st.iter_rows(min_col=min_col, min_row=min_row, max_col=max_col, max_row=max_row):
for cell in row:
cell.value = top_left_cell_value
else:
print(f"Only the top left cell {mcr.split(':')[0]} will contain the data!")
wb.save('merged_tmp.xlsx')
--UPDATE--
I discovered that the uitable does not register a 'second click' when t.ColumnEditable = true. When this is true, MATLAB waits until you personally deselect the cell to begin registering new clicks. Hence, that entire time it expects that new clicks are edits to the cell. Turn t.ColumnEditable to false and consecutive clicks register as new actions.
--
The CellSelectionCallback only seems to register clicks in new cells. For example, the following only displays 'src' and 'event' during the first click to any particular cell:
close all;
f = figure('Position',[50,62,1340,326],'Units','pixels'); % set figures so they're stacked
f.Name = 'Debugging table';
t = uitable(f,'Units','normalized','Position',[.05,.05,.9,.9]);
t.CellSelectionCallback = #cellSelected;
t.ColumnName = {};
t.RowName = {};
t.Data = magic(10);
t.FontSize = 10;
t.FontName = 'AppleGothic';
function [src,event] = cellSelected(src,event)
src
event
end
Can anyone provide a method that branches off of something like this that would allow the code inside 'cellSelected' to run on more than one consecutive click to a single cell in the active uitable? Thanks in advance.
--UPDATE--
I discovered that the uitable does not register a 'second click' when t.ColumnEditable = true. When this is true, MATLAB waits until you personally deselect the cell to begin registering new clicks. Hence, that entire time it expects that new clicks are edits to the cell. Turn t.ColumnEditable to false and consecutive clicks register as new actions that independently trigger the cellSelected callback function.
--
I'm trying to implement mouse selection for my game. When I QueryAABB it looks like it's treating objects much larger than they really are.
Here's what's going on in the image
The blue box is an actor containing a body that I'd like to select
The outline on the blue box is drawn by Box2DDebugRenderer
The mouse selects a region on the screen (white box), this is entirely graphical
The AABB is converted to meters and passed to QueryAABB
The callback was called for the blue box and turned it red
The green outline left behind is a separate body to check if my conversions were correct, this is not used for the actual selection process
It seems to be connected to my meter size, the larger it is, the more inaccurate the result is. At 1 meter = 1 pixel it works perfectly.
Meter conversions
val MetersToPixels = 160f
val PixelsToMeters = 1/MetersToPixels
def toMeters(n: Float) = n * PixelsToMeters
def toPixels(n: Float) = n * MetersToPixels
In the image I'm using MetersToPixels = 160f so the inaccuracy is more visible, but I really want MetersToPixels = 16f.
Relevant selection code
val x1 = selectPos.x
val y1 = selectPos.y
val x2 = getX
val y2 = getY + getHeight
val (l,r) =
if (x2 < x1)
(x2,x1)
else
(x1,x2)
val (b,t) =
if (y2 < y1)
(y2,y1)
else
(y1,y2)
world.QueryAABB(selectCallback, toMeters(l),toMeters(b), toMeters(r),toMeters(t))
This code is inside the act method of my CursorActor class. And selectPos represents the initial point where the use pressed down the left mouse button and getX and getY are Actor methods giving the current position. The next bit sorts them because they might be out of order. Then they are converted to meters because they are all in pixel units.
selectCallback: QueryCallback
override def reportFixture(fixture: Fixture): Boolean = {
fixture.getBody.getUserData match {
case selectable: Selectable =>
selected += selectable
true
case _ => true
}
}
Selectable is a trait that sets a boolean flag internally after the query which helps determines the color of the blue box. And selected is a mutable.HashSet[Selectable] defined inside of CursorActor.
Other things possibly worth noting
I'm new to libgdx and box2d.
The camera is scaled x2
My Box2DDebugRenderer uses the camera's combined matrix multiplied by MetersToPixels
From what I was able to gather, QueryAABB is naturally inaccurate for optimization. However, I've hit a roadblock with libgdx because it doesn't have any publicly visible function like b2testOverlap and from what I understand, there's no plan for there to be one any time soon.
I think my best solution would probably be to use jbox2d and pretend that libgdx's physics implementation doesn't exist.
Or as noone suggested I could add it to libgdx myself.
UPDATE
I decided to go with a simple solution of gathering the vertices from the fixture's shape and using com.badlogic.gdx.math.Intersector against the vertices of the selection. It works I guess. I may stop using QueryAABB all together if I decide to switch to using a sensor for the select box.
The table cell is edit with a simple click, I want it to be edit only on double click. Simple click will select the cell.
I'm use this property of uitable:
set(hTable, 'Data',data,...
'ColumnEditable', edit,...
First you need to set the cell editabiliy to false by default:
set(hTable,'ColumnEditable', [false false ...]); %accordingly your number of columns
and introduce a CellSelectionCallback:
set(hTable,'CellSelectionCallback',#cellSelect);
which calls the following function within the same script
function cellSelect(src,evt)
getstate = get(src,'ColumnEditable'); %gets status of editability
index = evt.Indices; %index of clicked cell
state = [false false ...]; %set all cells to default: not editable
state(index) = ~getstate(index); %except the clicked one, was it
%already false before set it true
set(src,'ColumnEditable', state) %pass property to table
end
and also a CellEditCallback:
set(hTable,'CellEditCallback',#cellEdit);
calling
function cellEdit(src,~)
state = [false false ...];
set(src,'ColumnEditable', state)
end
minimal example
function minimalTable
h = figure('Position',[600 400 402 100],'numbertitle','off','MenuBar','none');
defaultData = {'insert number...' , 'insert number...'};
uitable(h,'Units','normalized','Position',[0 0 1 1],...
'Data', defaultData,...
'ColumnName', [],'RowName',[],...
'ColumnWidth', {200 200},...
'ColumnEditable', [false false],...
'ColumnFormat', {'numeric' , 'numeric'},...
'CellSelectionCallback',#cellSelect);
end
function cellSelect(src,evt)
getstate = get(src,'ColumnEditable');
index = evt.Indices;
state = [false false];
state(index) = ~getstate(index);
set(src,'ColumnEditable', state)
end
function cellEdit(src,~)
state = [false false];
set(src,'ColumnEditable', state)
end
As you figured out this is not always working. Because you have the same issues like I had before with popup menus. It's exactly the same problem: ColumnEditable is just a row vector and not a matrix. I had to deal with the ColumnFormat property, which is also just a row vector. If the double click feature is really important to you, you can consult the following two answers:
Is it possible to prevent an uitable popup menu from popping up? Or: How to get a callback by clicking a cell, returning the row & column index?
How to deselect cells in uitable / how to disable cell selection highlighting?
The threads basically suggest to create a unique uitable for every single row, so that every single row has a unique ColumnEditable property. That's the only solution so far.
I'm afraid there is no simple solution. I can't offer you further help, except the complicated workarounds of the other answers. Or just use the simple one above and live with the little drawbacks.
Although this thread is old but in my opinion still valuable to some users.
I have tested the following with R2010b 32bit.
I have achieved editing only on double click simply by setting
set(hTable,'CellSelectionCallback',#tableCellSelectCB,'ColumnEditable',true)
and defining its function the following
function tableCellSelectCB(~,~)
try
h.jtable.getCellEditor().stopCellEditing();
catch
end
end
where h.jtable refers to the underlying java object of your uitable.
This way, I can select even single and multiple cells, without going into edit mode. On a double click on a single cells lets me edit its contents.
Extension to have individual editable rows
I wanted to have checkboxes in the top row and non-editable (not directly at least) data in the rest of the table. You can easily modify the above:
function tableCellSelectCB(~,evd)
if evd.Indices(1) > 1
try
h.jtable.getCellEditor().stopCellEditing();
catch
end
end
end
I have a vertical panel containing two rows, say row 1 and row 2, each
row contains couple of widgets, now i need to allow the user to drag
and drop widgets between row 1 and row 2, here is what i did
_handler = new DragHandler() { .... };
_widgetDragController = new PickupDragController(boundaryPanel, false);
_widgetDragController.setBehaviorMultipleSelection(false);
_widgetDragController.addDragHandler(_handler);
then for each row, create panel to hold widgets and assign a drop controller:
VerticalPanelWithSpacer vPanel = new VerticalPanelWithSpacer();
// initialize a widget drop controller for the current column VerticalPanelDropController
widgetDropController = new VerticalPanelDropController(vPanel);
_widgetDragController.registerDropController(widgetDropController);
how can i find the drop target (namely which row) when i dnd widgets between row 1 and row 2? is there any way the _widgetDragController can tell which drop controller got involved and then i can further call getDropTarget() from the drop controller?
You could implement the functionality in VerticalPanelDropController.onDrop(DragContext), which gets called when the users drop on that drop controller. The drop controller knows the VerticalPanelWithSpacer it belongs to, and the dragContext contains information such as the x, y coordinates. You could use this information (the y coordinate & the coordinates of the widget) to calculate the row which should be added (although you might need to take scrolling etc into account, which makes it a bit more tricky). Hope that helps :-)