Setting row Span in QTableView using Python? - python

I am trying to set rowspan on second column of my QTableView but somehow logically i am missing something. i am only able to get A and B but not C. Plus i am getting warning QTableView::setSpan: span cannot overlap and QTableView::setSpan: single cell span won't be added
My code snippet is:-
startspan = 0
for i, tcname in enumerate(tcfilename):
if tcfilename[i]:
if i > 0:
print '#######################'
print 'startspan = '+str(startspan)+' i = '+str(i)
if tcname == tcfilename[i-1]:
#setSpan (row, column, rowSpan, columnSpan)
print 'if (from_row, till_row) '+str(startspan)+' '+str(i)
table_view.setSpan(startspan, 1, i, 1);
elif tcname != tcfilename[i-1]:
print 'Else no span (from_row, till_row) '+str(startspan)+' '+str(i)
table_view.setSpan(startspan, 1, i, 1);
if i == 1:
startspan = 0
else:
startspan = i
else:
break

Did this with simple two line code below
for toRow, tcname in enumerate(tcfilename):
table_view.setSpan(tcfilename.index(tcname), 1, tcfilename.count(tcname), 1)

I made a nifty little function to solve this.. Had recursion but then optimized it without recursion.. feed it a table and a data set
def my_span_checker(self, my_data, table):
for i in range(len(my_data)):
my_item_count = 0
my_label = table.item(i, 0).text()
for j in range(len(my_data)):
if table.item(j, 0).text() == my_label:
my_item_count += 1
if my_item_count != 1:
table.setSpan(i, 0, my_item_count, 1)

Related

Relocate the table index in python 3

Query = search _entry.get()
Sql = *SELECT FROM customers where last_name = %s"
Data = (query,)
Result = my_cursor. Execute (sql, data)
Result = my_cursor. fetchall ()
If not result :
Result = "record not found... "
Query_label = Label(search _customer _window, text =result)
Query_label. Place (x=40,y=130)
else :
For index, x in enumerate (result) :
Num =0
Index +=2
For y in x:
Query_label = Label(search _customer_window, text=y)
Query_label.grid(row=index,column=num)
Num +=1
I set the value of index to 2 but nothing happens. Thanks for your help.
When I run the program, the label (query_lqbel) is shown at top left side of the window (row 0, column =0), how can I change the location of label. Its actually a label on which some data are shown.

PyQt5: Get row number from button-menu action in QTableView index-widget

Basically, I have a QTableView and the last column of each row contains a QMenu where if triggered, the row should be deleted. I tried the code below, but if I click on the menu that is in a row number > 1, the returned rowNum is -1:
Code:
def addrowIntable(self, a, b):
Column1 = QStandardItem("%s" % (a))
Column2 = QStandardItem("%s" % (b))
actionBTN = QPushButton("")
actionMenu = QMenu()
self.RemList = QtWidgets.QAction("Remove row", actionMenu)
actionMenu.addAction(self.RemList)
actionMenu.raise_()
actionBTN.setMenu(actionMenu)
self.rulesWhitelistWidgetModel.appendRow([Column1, Column2])
self.rulesWhiteListFileTBL.setIndexWidget(
self.rulesWhitelistWidgetModel.index(self.rulesWhitelistWidgetModel.rowCount() - 1,
self.rulesWhiteListFileTBL.model().columnCount() - 1), actionBTN)
self.RemList.triggered.connect(lambda: self.deleteRow("Hello"))
def deleteRow(self, str):
rowNum = self.rulesWhiteListFileTBL.rowAt(self.rulesWhiteListFileTBL.viewport().mapFromGlobal(self.sender().parent().pos()).y())
print(self.rulesWhiteListFileTBL.indexAt(self.sender().parent().pos()).row())
print(rowNum)
I just need to know which row number was the sender from inside deleteRow where I could then use model.removeRow() to delete it.
The main reason why your code doesn't work as expected is because you set the menu as the parent of the action. A menu is a popup window, so its position will be in global coordinates, whereas you want the position relative to the table. A simple way to achieve this is to make the button the parent of the action instead.
The following revision of your code should do what you want:
def addrowIntable(self, a, b):
Column1 = QStandardItem("%s" % (a))
Column2 = QStandardItem("%s" % (b))
actionBTN = QPushButton()
actionMenu = QMenu()
actionRem = QtWidgets.QAction("Remove row", actionBTN)
actionMenu.addAction(actionRem)
actionBTN.setMenu(actionMenu)
self.rulesWhitelistWidgetModel.appendRow([Column1, Column2])
self.rulesWhiteListFileTBL.setIndexWidget(Column2.index(), actionBTN)
actionRem.triggered.connect(lambda: self.deleteRow("Hello"))
def deleteRow(self, str):
pos = self.sender().parent().pos()
index = self.rulesWhiteListFileTBL.indexAt(pos)
self.rulesWhitelistWidgetModel.removeRow(index.row())

How create a sqlalchemy delete query with multiples parameter from a loop

I'm new in python and sqlalchemy.
I already have a delete method working if I construct the where conditions by hand.
Now, I need to read the columns and values from an enter request in yaml format and create the where conditions.
#enter data as yaml
items:
- item:
table: [MyTable,OtherTable]
filters:
field_id: 1234
#other_id: null
Here is what I try and can't go ahead:
for i in use_case_cfg['items']:
item = i.get('item')
for t in item['table']:
if item['filters']:
filters = item['filters']
where_conditions = ''
count = 0
for column, value in filters.items():
aux = str(getattr(t, column) == bindparam(value))
if count == 0:
where_conditions += aux
else:
where_conditions += ', ' + aux
count += 1
to_delete = inv[t].__table__.delete().where(text(where_conditions))
#to_delete = t.__table__.delete().where(getattr(t, column) == value)
else:
to_delete = inv[t].__table__.delete()
CoreData.session.execute(to_delete)
To me, it looks ok, but when I run, I got the error below:
sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter '9876'
[SQL: DELETE FROM MyTable WHERE "MyTable".field_id = %(1234)s]
[parameters: [{}]]
(Background on this error at: http://sqlalche.me/e/cd3x)
Can someone explain to me what is wrong or the proper way to do it?
Thanks.
There are two problems with the code.
Firstly,
str(getattr(t, column) == bindparam(value))
is binding the value as a placeholder, so you end up with
WHERE f2 = :Bob
but it should be the name that maps to the value in filters (so the column name in your case), so you end up with
WHERE f2 = :f2
Secondly, multiple WHERE conditions are being joined with a comma, but you should use AND or OR, depending on what you are trying to do.
Given a model Foo:
class Foo(Base):
__tablename__ = 'foo'
id = sa.Column(sa.Integer, primary_key=True)
f1 = sa.Column(sa.Integer)
f2 = sa.Column(sa.String)
Here's a working version of a segment of your code:
filters = {'f1': 2, 'f2': 'Bob'}
t = Foo
where_conditions = ''
count = 0
for column in filters:
aux = str(getattr(t, column) == sa.bindparam(column))
if count == 0:
where_conditions += aux
else:
where_conditions += ' AND ' + aux
count += 1
to_delete = t.__table__.delete().where(sa.text(where_conditions))
print(to_delete)
session.execute(to_delete, filters)
If you aren't obliged to construct the WHERE conditions as strings, you can do it like this:
where_conditions = [(getattr(t, column) == sa.bindparam(column))
for column in filters]
to_delete = t.__table__.delete().where(sa.and_(*where_conditions))
session.execute(to_delete, filters)

Changing Image.Grab.grab(value) without retyping

A list helped me make a loop which grabs a part of the screen and compare it to a existing RGB value. Final code is in final edit. Full learnprocess is shown below.
I'm new to coding in general. I am using pixels do verify RGB value of a pixel which declares position of player. But in stead of re-typing location = ImageGrab.grab(position) can I change the position?
seat0 = (658,848,660,850) #btn
seat1 = (428,816,429,817) #co
seat2 = (406,700,407,701) #hj
seat3 = (546,653,547,654) #lj
seat4 = (798,705,799,706) #bb
seat5 = (769,816,770,817) #sb
btnpos = ImageGrab.grab(seat0)
position = btnpos.load()
btn = (251,0,8)
if position[0,0] == btn:
print('Button')
elif ????
So I want to change seat0 (in imagegrab) to seat1 without re-typing the code. Thanks for the help
EDIT1: So I tried Marks suggestion, not sure what I'm doing wrong.
positie = ["(658,848,660,850)","(428,816,430,818)","(406,700,408,702)","(546,653,548,655)","(798,705,799,706)","(769,816,770,817)"]
btn = (251,0,8)
btnpos = ImageGrab.grab(positie[0])
btncheck = btnpos.load()
btn [0,0] not in positie[0]
I get "ValueError: too many values to unpack (expected 4)"
I am trying to RGB value of positie[0] and it has to match btn. if it doesn't match to btn then it has to check positie[1], until it returns true.
Edit2:
Thanks so far Mark. I am so bad at loops.
positie = [(658,848,660,850),(428,816,430,818),(406,700,408,702),(546,653,548,655),(798,705,799,706),(769,816,770,817)]
btn = (251,0,8)
btnpos = ImageGrab.grab(positie[0])
btncheck = btnpos.load()
for x in positie:
#btncheck = btnpos.load()
if btncheck[0,0] ==btn:
print("positie is BTN")
else:
btnpos = (positie[++1])
print(btnpos)
how do I change btnpos with adding up instead of re-typing everything?
So it's supposed to grab first item in list and compare it to btn. If it's correct it can break, if it's wrong it has to compare btn with second item in list.
If true it gives me the position. If false:
Now it prints list[1] six times.
Thank you for your patience
FINAL EDIT: Thank you Mark.
positie = [(658,848,660,850),(428,816,430,818),(406,700,408,702),(546,653,548,655),(798,705,799,706),(769,816,770,817)]
btn = (251,0,8)
counter = 0
max_index = len(positie) - 1
while counter <= max_index:
btnpos = ImageGrab.grab(positie[counter])
btncheck = btnpos.load()
if btncheck[0,0] == btn:
print("Positie")
break
else:
print("controleert de volgende")
counter = counter + 1

how to disable all columns apart from one column in Qtablewidget PYQT - python

Problem Statement:
Disable specific columns and enable specific row on bases of current row index.
I am working on Qtablewidget i tried following code this working fine for disable.
i wanted to enable tablewidget row contents on bases of row index .
when i clicked pushbutton that row should be enable.I am new to the stackoverflow please guide me.I am tring to enable tablewidget cell,pushbutton,combobox i am not getting please guide me how to enble particular row on bases of index.
Code :
self.tableWidget = QtGui.QTableWidget(self.centralwidget)
self.tableWidget.setColumnCount(4)
myresult = [(u'sandeep', u'checkbox'), (u'shivaraj', u'checkbox')]
for row, result in enumerate(myresult):
self.tableWidget.insertRow(self.tableWidget.rowCount())
for column, value in enumerate(result):
item = QtGui.QTableWidgetItem(str(value))
if column == 1:
if (value == "textbox"):
self.cb = QtGui.QComboBox()
lis = ("---select---", "description", "multiple_input")
self.cb.addItems(lis)
self.cb.setCurrentIndex(1)
self.tableWidget.setCellWidget(row, column, self.cb)
self.cb.setEnabled(False)#this is for combobox disable
elif (value == "checkbox"):
self.cb = QtGui.QComboBox()
lis = ("---select---", "description", "multiple_input")
self.cb.addItems(lis)
self.cb.setCurrentIndex(2)
self.tableWidget.setCellWidget(row, column, self.cb)
self.cb.setEnabled(False)#this is for combobox disable
self.tableWidget.setItem(row, column, item)
item.setFlags(QtCore.Qt.ItemIsEnabled)#this is for text non editable
self.btn_sell = QtGui.QPushButton('Edit')
self.btn_sell1 = QtGui.QPushButton('Delete')
self.btn_sell1.setEnabled(False)#this for button disble
self.tableWidget.setCellWidget(row, 2, self.btn_sell)
self.tableWidget.setCellWidget(row, 3, self.btn_sell1)
self.btn_sell.clicked.connect(self.edit)
def edit(self):
index = self.tableWidget.currentRow()
print index
self.table = QtGui.QTableWidget()
self.table.setGeometry(QtCore.QRect(220, 100, 881, 100))
self.table.setColumnCount(4)
self.table.setRowCount(1)
self.table.setColumnWidth(0, 120)
self.table.setColumnWidth(1, 500)
self.table.setColumnWidth(2, 120)
self.table.setColumnWidth(3, 120)
indexes = self.tableWidget.currentRow()
widget = self.tableWidget.cellWidget(indexes, 2)
# print widget
if isinstance(widget, QtGui.QComboBox):
h = str(widget.currentText())
if (h == "multiple_input"):
j = "checkbox"
elif (h == "description"):
j = "textbox"
if (j == "textbox"):
self.cb = QtGui.QComboBox()
lis = ("---select---", "description", "multiple_input")
self.cb.addItems(lis)
self.cb.setCurrentIndex(1)
self.table.setCellWidget(0, 2, self.cb)
[enter image description here][1]elif (j == "checkbox"):
self.cb = QtGui.QComboBox()
lis = ("---select---", "description", "multiple_input")
self.cb.addItems(lis)
self.cb.setCurrentIndex(2)
self.table.setCellWidget(0, 2, self.cb)
n = [str(self.tableWidget.item(indexes, 0).text())]
for x in n:
f = ''.join(map(str, x))
self.table.setItem(0, 0, QtGui.QTableWidgetItem(f))
n1 = [str(self.tableWidget.item(indexes, 1).text())]
# print n1
for i in n1:
s = ''.join(i)
self.table.setItem(0, 1, QtGui.QTableWidgetItem(s))
self.li = QtGui.QPushButton("Update")
self.table.setCellWidget(0, 3, self.li)
self.li.clicked.connect(self.edit_data)
self.table.show()
click on below link has image.
Try the above code:
Select row and click on edit button it will take the current index row values into the separate table `where we can edit and update the values.This is the one way i have tried to update the value it works fine.

Categories