PyQT : Transfer between two TableView - python

I would like to transfer data between two QtTableView. To do that, I first select the row to transfer then click on "to_X_table".
But I don't understand how to fill the second tableview with the first one.
I tried :
self.to_X_table.clicked.connect(self.to_X_tableView)
def to_X_tableView(self):
self.proxy = QtCore.QSortFilterProxyModel()
self.proxy.setSourceModel(self.tableWidget_Input_Col.selectionModel())
self.tableView_X.setModel(self.proxy)
self.tableView_X.resizeColumnsToContents()
I get this message :
TypeError : setSourceModel(self,‌​QAbstractItemModel) : 1 argument unexpected type QItemSelectionModel
I'dont really know what self.tableWidget_Input_Col.selectionModel() return. I guess it was a model. But seems not.
I also tried to create my own model like this (following this post Get data from every cell from a QTableView)
def to_X_tableView(self):
indexes = self.tableWidget_Input_Col.selectionModel().selectedRows()
self.model = QtGui.QStandardItemModel()
for index in sorted(indexes):
print('Row %d is selected' % index.row())
self.model.invisibleRootItem().appendRow(
QtGui.QStandardItem(self.tableWidget_Input_Col.model.index(index.row, 0)))
self.proxy = QtCore.QSortFilterProxyModel()
self.proxy.setSourceModel(self.tableWidget_Input_Col.selectionModel())
self.tableView_X.setModel(self.proxy)
self.tableView_X.resizeColumnsToContents()
but I get this error :
Traceback (most recent call last):
File "ChartGUI.py", line 151, in to_X_tableView
QtGui.QStandardItem(self.tableWidget_Input_Col.model.index(index.row, 0)
AttributeError: 'builtin_function_or_method' object has no attribute 'index'

Finaly, I solve my problem. I didn't consider the model the first time.
Here :
self.modelX = QtGui.QStandardItemModel()
indexes = self.tableWidget_Input_Col.selectionModel().selectedIndexes()
temp=self.tableWidget_Input_Col.selectionModel().model() # need to consider the model !
for index in sorted(indexes):
self.modelX.invisibleRootItem().appendRow(
QtGui.QStandardItem(str(temp.data(index))))
self.proxy = QtCore.QSortFilterProxyModel()
self.proxy.setSourceModel(self.modelX)
self.tableView_X.setModel(self.proxy)
self.tableView_X.resizeColumnsToContents()

Related

TypeError: 'NoneType' object is not subscriptable in a int object

Here is a function to check the data and update it
div , update are my mongodb collection object
def data_updater(user1_id,code):
device_id = dvi.find_one({"user_id":user1_id},{"_id":0,"user_id":0})["device_id"]
prv_data = update.find_one({"device_id":device_id},{"_id":0,"device_id":0})
prv_date = prv_data["date"]
msg = prv_data["message"]
if prv_date < current_date and msg != code:
x = update.find_one_and_update({"device_id":id,},{"$set":message":code,"date":current_date}})
print(x.acknowledged)
and when I am calling the function it is giving TypeError data_updater(95626,972681)
the error
Traceback (most recent call last):
File line 170, in <module>
data_updater(95626,972681)
File line 71, in data_updater
device_id = dvi.find_one({"user_id":int(user1_id)},{"_id":0,"user_id":0})["device_id"]
TypeError: 'NoneType' object is not subscriptable
I am not able to find any mistake please help
Your context isn't very clear, however, from the error trace as generated it seems that your find_one() function returns None with the arguments as passed and you are trying to access the value for the key device_id. I recommend you refactor your find_one() function or make use of the following code to resolve the issue at hand:
def data_updater(user1_id,code):
try:
device_id = dvi.find_one({"user_id":user1_id},{"_id":0,"user_id":0})["device_id"]
prv_data = update.find_one({"device_id":device_id},{"_id":0,"device_id":0})
prv_date = prv_data["date"]
msg = prv_data["message"]
if prv_date < current_date and msg != code:
x = update.find_one_and_update({"device_id":id,},{"message":code,"date":current_date}})
print(x.acknowledged)
except TypeError:
print('No value found for specified parameters :/')
PS: I also didn't understand the use of $ in your code, so I removed it thinking of it as a mistake. Hope this helps! 😊

Setting up combobox model with QtSql model gives an error

I have the following code:
uic.loadUi("mainwindow.ui", self)
self.db = QSqlDatabase.addDatabase('QSQLITE')
self.db.setDatabaseName('people.db')
self.db.open()
try:
if self.db.isOpen():
print('DB open')
# self.pushButtonClear.clicked.connect(self.clearFields)
# self.pushButtonSave.clicked.connect(self.insertRowToModel)
self.pushButtonDelete.clicked.connect(self.deleteTableRow)
self.model = QSqlRelationalTableModel(db=self.db)
self.model.setTable("person")
self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
self.group_index = self.model.fieldIndex("GroupId") #foreign key
self.model.setRelation(self.group_index, QSqlRelation("Groups", "GroupId", "GroupName"))
self.model.select()
self.relModel = self.model.relationModel(self.group_index)
self.comboBoxGroup.setModel(self.relModel)
self.comboBoxGroup.setModelColumn(self.relModel.fieldIndex("GroupName"))
self.tableView.setModel(self.model)
self.mapper = QDataWidgetMapper()
self.mapper.setModel(self.model)
self.mapper.setItemDelegate(QSqlRelationalDelegate(self))
self.mapper.addMapping(self.lineEditId, 0)
self.mapper.addMapping(self.lineEditForename, 1)
self.mapper.addMapping(self.lineEditSurename, 2)
self.mapper.addMapping(self.dateEditBirthday, 3)
self.mapper.addMapping(self.lineEditCity, 4)
self.mapper.addMapping(self.comboBoxGroup, self.group_index)
self.mapper.toFirst()
except:
self.db.close()
print('Exception raised')
in line: self.comboBoxGroup.setModelColumn(self.relModel.fieldIndex("GroupName"))
it gives an AttributeError: 'NoneType' object has no attribute 'fieldIndex'
because the self.relModel = self.model.relationModel(self.group_index) results in a None type. It could not be setup. When i enter the column index as a number like this: self.comboBoxGroup.setModelColumn(self.relModel.fieldIndex(1)) the data shows up at least, but the combobox is not filled. What is going wrong here?
I have found the problem:
self.group_index = self.model.fieldIndex("group") #foreign key
field name was incorrect. Now it works but only gives entries where there is
an entry in the group table (inner join)

i inserting data in to a table but raises the error

This is the code
def parse_listings(self, response):
'''
content = ''
with open('incidec1.html', 'r' ) as f:
for line in f.read():
content += line
response = Selector(text=content)
brand = response.css('div[class="fs21"]').css('span').css('a::text').get()
title = response.css('div[class="klavikab lilac"]').css('span::text').get()
t = (id, brand,title)
cur.execute('''INSERT INTO products VALUES(%s,%s,%s,%s,%s)''',(id, brand, title))
mydb.commit()
print('complete.')
if __name__ == '__main__':
incidecoderspider.parse_listings(incidecoderspider,'')'
this the output error:
Traceback (most recent call last):
File "incidecoder1.py", line 98, in <module>
incidecoderspider.parse_listings(incidecoderspider,'')
File "incidecoder1.py", line 80, in parse_listings
cur.execute('''INSERT INTO products VALUES(%s,%s,%s,%s,%s)''',(id, brand, title, photo, ingredients))
AttributeError: 'builtin_function_or_method' object has no attribute 'translate'
i tried very much but can't understanfd what is the problem.
You're trying to use a value that you didn't define: id. Normally, this would get you an "undefined symbol" error. However, id is defined: it's a built-in function.
Simply change the variable name so that you don't collide with a built-in item (such as product_id), and then give that variable a value.

flask sqlalchemy query with keyword as function argument

I am stuck with a query in a function. here is my code:
def action(changePin, action):
pins = Pins.query.all()
changePin = int(changePin)
deviceName = Pins.query.filter_by(pin=changePin, name)
if action == "on":
GPIO.output(changePin, GPIO.HIGH)
print("turned ", deviceName , " on")
if action =="off":
GPIO.output(changePin, GPIO.LOW)
print("turned ", deviceName , " off")
for pin in pins:
db.session.commit()
The error for this is
File "<stdin>", line 4
SyntaxError: positional argument follows keyword argument
In line 4 I want to find the name of the pin relating to the pin "changePin", this is adapted code from a tutorial, here is the origional code where a dictionary holds the pin information not a database, code:
deviceName = pins[changePin]['name']
I have tried numerous different ways but none work, here is a list of the different versions of line 4:
deviceName = Pins.query.filter_by(changePin=pin).name
deviceName = Pins.query.filter_by(changePin, name=name)
deviceName = Pins.query.filter_by(Pins.pin=changePin, Pins.Name)
deviceName = Pins.query(Pins.pin=changePin, Pins.Name)
deviceName = Pins.query(**changePin, Pins.name)
deviceName = Pins.query(**changePin)
deviceName = db.session.filter_by(Pins.changePin)
deviceName = db.session(Pins).filter_by(pin=changePin)
and many other variations, I have read the sqlalchemy docs and the flask docs, but I have not seen any comparisons, I have looked at and tried this; flask sqlalchemy query with keyword as variable
but got this;
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in action
TypeError: BaseQuery object argument after ** must be a mapping, not int
this is my models.py code;
class Pins(db.Model):
id = db.Column(db.Integer, primary_key=True)
pin = db.Column(db.Integer, index=True, unique=True)
name = db.Column(db.String(64))
upDown = db.Column(db.String(4))
state = db.Column(db.String(9))
def __repr__(self):
return '<Valves {}>'.format(self.pin)
Querying with function on Flask-SQLAlchemy model gives BaseQuery object is not callable error
Dear Menno
Thank you for comming back to me I have followed your advice and it works!!!
rows = Pins.query.filter_by(pin=changePin).all()
deviceName = rows[0].name
I don't understand how the "rows[0].name" part works but it does,
thank you thank you
help
regards
Paul
A filter_by expression selects rows, not fields. From the documentation: "apply the given filtering criterion to a copy of this Query, using keyword expressions.". Name is not a keyword expression, just a name.
Also, after building the query, you have to run it. You do that by calling all() on it:
deviceName = Pins.query.filter_by(pin=changePin).all()
Letś also change the name of the outcome:
rows = Pins.query.filter_by(pin=changePin).all()
Calling that returns a list with zero or more rows, hence the name. rows[0] (the first row) is what you want. After you have a row, a field becomes an attribute of the row: rows[0].name. You can also use one() to get a unique row.
If you still need that: To limit the columns that are returned use load only cols

TypeError: 'type' object has no attribute '__getitem__' in pandas DataFrame

I was trying to analyse the play-by-play data of a basketball team
What I did was to read a csv file into a DataFrame object.
I want to preserve the functionality of the DataFrame object while adding in new attributes to the existing object. Thus I wrote a class called Basketball:
from data_math import *
import pandas as pd
class Basketball(pd.DataFrame):
def __init__(self,*args,**kargs):
pd.DataFrame.__init__(self,*args,**kargs)
self.FGM = calculate_FGM(pd.DataFrame)
self.FGA = calculate_FGA(pd.DateFrame)
self.FGP = self.FGM / self.FGA
self.M3 = calculate_3M(pd.DataFrame)
self.A3 = calcualte_3A(pd.DataFrame)
self.P3 = self.M3 / self.A3
self.FTM = calcualte_FTM(pd.DataFrame)
self.FTA = calculate_FTA(pd.DataFrame)
self.FTP = self.FTM / self.FTA
# self.P = score_calculate(pd.DataFrame)
I wrote another data_math.py file to help calculate the different attributes I wanted to include into the Basketball class.
from pandas import DataFrame
def score_calculate(df):
df_pt_scored = df[((df['etype']=='shot') & (df['result']=='made'))]
df_ft_scored = df[((df['etype']=='free throw') & (df['result']=='made'))]
return df_pt_scored['points'].sum()+len(df_ft_scored.index)
def calculate_FGM(df):
cond_pt = (df['etype']=='shots') & (df['results']=='made')
cond_ft = (df['etype']=='freethrow') & (df['results']=='made')
return len(df[cond_pt].index)+len(df[cond_ft].index)
def calculate_FGA(df):
shot_cond= df['etype']=='shot'
free_throw_cond = df['etype']=='free throw'
return len(df[shot_cond].index)+len(df[free_throw_cond].index)
def calculate_3M(df):
cond_3M= (df['etype']=='shot')&(df['type']=='3pt')&(df['result']=='made')
return len(df[cond_3M].index)
def calcualte_3A(df):
cond_3A = (df['etype']=='shot')&(df['type']=='3pt')
return len(df[cond_3A].index)
def calculate_FTM(df):
cond_FTM =(df['etype']=='free throw') & (df['result']=='made')
return len(df[cond_FTM].index)
def calcualte_FTA(df):
cond_FTA =(df['etype']=='free throw')
return len(df[cond_FTA].index)
In the end I start my program from main.py which I hope would give me the correct output. However while executing on this line:
team1= Basketball(tm1)
I received the following Traceback
Traceback (most recent call last):
File "/Users/luoyicheng/Developer/STAR-Research/data_analysis/source code/main.py", line 20, in <module>
team1= Basketball(tm1)
File "/Users/luoyicheng/Developer/STAR-Research/data_analysis/source code/Basketball.py", line 6, in __init__
self.FGM = calculate_FGM(pd.DataFrame)
File "/Users/luoyicheng/Developer/STAR-Research/data_analysis/source code/data_math.py", line 9, in calculate_FGM
cond_pt = (df['etype']=='shots') & (df['results']=='made')
TypeError: 'type' object has no attribute '__getitem__'
I am new to python programming and could not figure out why this error has occurred. To my understanding, this error means I am unable to use indexing feature of the DataFrame. However, if I try to code in my main function similar things I am able to get the output I want. I am also not clear of how to extend the existing DataFrame class so that I can still access the methods in the DataFrame class while extending the team1 object to have attributes such as FGM, FGA, etc.
The idea of extending this class is to allow me to pass any DataFrame object in the Basketball() so that I can have an object with extending attributes and methods. I think I also lack an understanding of the use of init and self.
Please don't blame for not describing the problem clearly as I am not familiar with all the terminology in OOP.
Thank you so much!
You're passing each function pd.DataFrame which is of type type:
In [11]: type(pd.DataFrame)
Out[11]: type
Hence the exception message.
You mean to be passing self (which is of type DataFrame):
self.FGM = calculate_FGM(pd.DataFrame)
...
should read:
self.FGM = calculate_FGM(self)
...

Categories