PyQt5下拉框连接数据库
时间: 2023-10-10 09:12:00 浏览: 223
Qt连接数据库
下面是一个简单的教程,展示如何在PyQt5中使用下拉框连接数据库:
1. 导入必要的库
```python
from PyQt5.QtWidgets import QApplication, QWidget, QComboBox
from PyQt5.QtSql import QSqlDatabase, QSqlQueryModel
```
2. 创建一个QWidget窗口和一个下拉框QComboBox
```python
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.combo = QComboBox(self)
```
3. 连接到数据库
```python
def connect_to_database(self):
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('mydatabase.db')
if not db.open():
print("Cannot establish a database connection")
return False
else:
print("Database connection established successfully")
return True
```
4. 将数据库中的数据填充到下拉框中
```python
def fill_combo(self):
query_model = QSqlQueryModel()
query_model.setQuery("SELECT name FROM mytable")
self.combo.setModel(query_model)
```
5. 将下拉框添加到QWidget中并显示
```python
self.fill_combo()
self.show()
```
完整代码如下所示:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QComboBox
from PyQt5.QtSql import QSqlDatabase, QSqlQueryModel
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.combo = QComboBox(self)
self.connect_to_database()
self.fill_combo()
self.show()
def connect_to_database(self):
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('mydatabase.db')
if not db.open():
print("Cannot establish a database connection")
return False
else:
print("Database connection established successfully")
return True
def fill_combo(self):
query_model = QSqlQueryModel()
query_model.setQuery("SELECT name FROM mytable")
self.combo.setModel(query_model)
if __name__ == '__main__':
app = QApplication([])
widget = MyWidget()
app.exec_()
```
阅读全文