我试图从 SQLite 数据库填充组合框,但没有提取任何内容。
我的代码
import sys
from PyQt6 import QtWidgets
from PyQt6.QtSql import QSqlTableModel
import sqlite3
from test_rt_sql import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.model = QSqlTableModel()
self.model.setTable('user')
self.model.select()
self.ui.comboBox.setModel(self.model)
self.ui.comboBox.currentIndexChanged.connect(self.comboBox_val)
self.show()
def comboBox_val(self):
conn = sqlite3.connect('C:/sqlite/test.db')
c = conn.cursor()
c.execute('SELECT name FROM user')
rows = c.fetchall()
for row in rows:
self.ui.comboBox.addItems(row)
conn.close()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())
我尝试在
addItems
中向其返回列表,但出现错误
self.ui.comboBox.addItems(self.comboBox_val)
TypeError: addItems(self, texts: Iterable[Optional[str]]): argument 1 has unexpected type 'method'
据我了解,它不喜欢论点
addItems
,即没有具体指数据,而是指方法。
返回列表的代码:
from PyQt6 import QtWidgets
from PyQt6.QtSql import QSqlTableModel
import sqlite3
from test_rt_sql import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.model = QSqlTableModel()
self.model.setTable('user')
self.model.select()
self.ui.comboBox.setModel(self.model)
self.ui.comboBox.addItems(self.comboBox_val)
self.show()
def comboBox_val(self):
global data1
conn = sqlite3.connect('C:/sqlite/test.db')
c = conn.cursor()
c.execute('SELECT name FROM user')
data1 = []
for row in c.fetchall():
data1.append(str(row))
return data1
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec()
数据库肯定连接好了,数据给定了。我是这样查的。
import sqlite3
def comboBox_val():
conn = sqlite3.connect('C:/sqlite/test.db')
c = conn.cursor()
c.execute('SELECT name FROM user')
rows = c.fetchall()
for row in rows:
print(row)
comboBox_val()
我一开始走错地方了。
连接到基础
create_connection
,然后已经 QSqlTableModel
,查询本身在 setQuery
中指定
import sys
from PyQt6 import QtWidgets
from PyQt6.QtSql import QSqlTableModel, QSqlDatabase
from test_rt_sql import Ui_MainWindow
def create_connection():
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("C:/sqlite/test.db")
return True
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
create_connection()
self.model = QSqlTableModel()
self.model.setTable('user')
self.model.setQuery('SELECT name FROM user')
self.model.select()
self.ui.comboBox.setModel(self.model)
self.show()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())