我正在使用PyQt和SQLAlchemy而SQLAlchemy不接受QStrings。有没有办法将QStrings传递给它,或者我必须每次都将QStrings转换为Python字符串?
谢谢。
以下是代码:
import sip
sip.setapi('QString', 2)
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, Float, MetaData, ForeignKey
from sqlalchemy.sql import select, and_
from PyQt4 import QtGui, QtCore
class DbUtils(object):
def __init__(self, db_file = None, parent = None):
self.db = None
self.db_connection = None
self.db_file = str(db_file)
def db_open(self):
self.db = create_engine('sqlite:///' + self.db_file)
self.db_connection = self.db.connect()
def db_close(self):
self.db_connection.close()
def db_create_voltdrop(self):
metadata = MetaData()
tb_cable_brands = Table('cable_brands', metadata,
Column('id', Integer, primary_key=True),
Column('brand', String)
)
tb_cable_types = Table('cable_types', metadata,
Column('id', Integer, primary_key=True),
Column('brand_id', None, ForeignKey('cable_brands.id')),
Column('type', String),
Column('alpha', String)
)
tb_cable_data = Table('cable_data', metadata,
Column('id', Integer, primary_key=True),
Column('type_id', None, ForeignKey('cable_types.id')),
Column('size', String),
Column('resistance', Float)
)
metadata.create_all(self.db)
def delete_cable_brand(self, cable_brand):
cable_brand = str(cable_brand)
metadata = MetaData()
metadata.bind = self.db
tb_cable_brands = Table('cable_brands', metadata, autoload = True)
cable_brands = select([tb_cable_brands.c.brand],
and_(tb_cable_brands.c.brand == cable_brand)
)
row = self.db_connection.execute(cable_brands)
data = row.fetchone()
if str(data[0]) == cable_brand:
cable_brands = tb_cable_brands.delete().where(tb_cable_brands.c.brand == cable_brand)
self.db_connection.execute(cable_brands)
return True
else:
return False
答案 0 :(得分:1)
您可以change the API to v2和PyQt始终使用常规Python字符串而不是QString
。
修改强>
案例1 :没有sip.setapi
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
c = QtGui.QComboBox()
c.addItems(["one","two"])
print c.currentText(), type(c.currentText())
c.show()
sys.exit(app.exec_())
# Outputs
one <class 'PyQt4.QtCore.QString'>
案例2 :使用sip.setapi
import sip
sip.setapi("QString",2)
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
c = QtGui.QComboBox()
c.addItems(["one","two"])
print c.currentText(), type(c.currentText())
c.show()
sys.exit(app.exec_())
# Outputs
one <type 'unicode'>