在这个综合示例中,我们将结合前面所学的内容,创建一个简单的 PyQt 应用程序,该程序具有以下功能:
- GUI 界面
- 数据库操作
- 网络通信
python
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
from PyQt5.QtNetwork import QTcpSocket
from PyQt5.QtCore import QIODevice
def connect_to_database():
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("mydatabase.db")
return db.open()
def execute_query():
query = QSqlQuery()
query.exec_("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, name TEXT)")
query.exec_("INSERT INTO people (name) VALUES ('John')")
def tcp_client():
socket = QTcpSocket()
socket.connectToHost("localhost", 8080)
if socket.waitForConnected():
socket.write(b"Hello, Server")
if socket.waitForReadyRead():
print("Received:", socket.readAll().data().decode())
socket.close()
app = QApplication([])
window = QWidget()
layout = QVBoxLayout()
button_db = QPushButton('Connect to Database')
button_db.clicked.connect(connect_to_database)
layout.addWidget(button_db)
button_query = QPushButton('Execute Query')
button_query.clicked.connect(execute_query)
layout.addWidget(button_query)
button_network = QPushButton('Network Request')
button_network.clicked.connect(tcp_client)
layout.addWidget(button_network)
window.setLayout(layout)
window.show()
app.exec_()
这个示例程序创建了一个具有三个按钮的简单 GUI 界面。每个按钮都连接到一个槽函数,这些槽函数分别执行数据库连接、数据库查询和网络请求。
希望这个综合示例能帮助你更好地理解如何使用 PyQt 进行实际开发!