【问题标题】:Does PYQT5 support all python libraries?PYQT5 是否支持所有 python 库?
【发布时间】:2018-02-15 00:31:46
【问题描述】:

我也是 python 和 GUI 编程的新手。

我需要构建一个前端 GUI 应用程序,而对于后端应用程序,我已经在 python 2.7 中构建了。

我的问题是,如果我在 PyQT 中开发一个前端应用程序,我是否能够在其中集成 python 代码(或)PYQT 是否支持套接字、线程等 python 模块?

【问题讨论】:

  • 你可以使用这些模块中的任何一个,但你必须使你的逻辑适应 GUI 的生命周期,例如你不应该有循环作为阻塞 True 因为同一个 GUI 有一个工作循环, 有几种选择,如果任务是周期性的且廉价的,则计时器,如果任务昂贵,更好的选择是使用线程,但考虑到您不应该从该线程更新 GUI,您必须使用信号和插槽来发送将数据发送到主线程并在那里更新它们。
  • 感谢 eyllanesc 的回复。我会记住这一点的。

标签: python python-2.7 pyqt pyqt4 pyqt5


【解决方案1】:

PyQt 不处理后端代码。它用于设置挂钩,以便当用户与 GUI 交互时,一些代码会在 Python 中启动。

换句话说,是的,您将能够实现诸如线程之类的东西。

这是一个示例,我单击了一个带有“钩子”的按钮来启动一个进程。在这种情况下,我将在另一个线程中启动该进程,以免 GUI 冻结。

import sys
import time
import threading
import datetime as dt
# Import from qtpy if you're running Anaconda3
from qtpy import QtCore, QtGui, QtWidgets
# Import from PyQt5 otherwise
# from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.resize(500, 220)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(400, 180, 93, 28))
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(10, 10, 471, 141))
        font = QtGui.QFont()
        font.setPointSize(20)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtCore.QCoreApplication.translate("MainWindow", "MainWindow", None))
        self.pushButton.setText(QtCore.QCoreApplication.translate("MainWindow", "Start", None))
        self.label.setText(QtCore.QCoreApplication.translate("MainWindow", "", None))


def main():
    # Continually update LineEdit with the time when the button is pressed
    # We can do this without freezing the GUI by launching update_time()
    # in another thread
    ui.pushButton.clicked.connect(lambda: threading.Thread(target=update_time).start())


def update_time():
    while True:
        current_time_text = dt.datetime.now().strftime('%b %d %Y %I:%M:%S %p')
        ui.label.setText(current_time_text)
        time.sleep(.01)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    main()
    sys.exit(app.exec_())

【讨论】:

  • 从另一个线程更改 UI,而不是运行 Qt 主循环的线程,这是灾难的根源,因为这不是线程安全的。
  • 你能帮我了解一下它是不安全的吗? @BlackJack
  • 从非主线程更新 GUI 会导致应用程序动态出现问题,请阅读以下内容以获取更多信息 doc.qt.io/qt-5/thread-basics.html
猜你喜欢
  • 2019-04-15
  • 2015-02-09
  • 2014-02-11
  • 2016-10-22
  • 2014-07-14
  • 2023-03-31
  • 2021-08-25
  • 2019-04-25
相关资源
最近更新 更多