【问题标题】:Using C++, how can I run a python file in Qt Designer?使用 C++,如何在 Qt Designer 中运行 python 文件?
【发布时间】:2017-11-18 15:53:29
【问题描述】:

我终于决定从 WxPython 过渡到 QT!我正在使用 Qt Designer5.9,但在放置新插槽时遇到问题。我的目标是在 GUI 上按下 button 并运行我在另一个 python 程序中编写的函数。

在 Qt Designer 中,我“go to slot”,选择 clicked() 并出现。

主窗口.cpp

void MainWindow::on_pushButton_2_clicked()
{

}

这正是我想要的,但语言错误!我的蟒蛇已经够糟糕了,更不用说别的了。所以通过运行this tutorial 我知道如果我通过ui->textEdit->append(("Hello World")); 我可以做一些自定义的事情,但是在使用 pyuic 转换为 .py 之后如何转换并不明显它正在实施。我的函数很容易导入,如下所示,我只需要知道放在哪里。

import myfunction
myfunction()

谁能给我一个例子,说明需要在 Qt Designer 中用 C++ 编写什么,以便我可以在 .ui 转换后调用我的 python 函数??

【问题讨论】:

  • 为什么不使用 PyQt?
  • 如果你想在 C++ 中使用嵌入 python,你可以参考这个链接。 doc.qt.io/archives/qq/qq23-pythonqt.html 但是,您需要先拥有可用的 python 库,这非常复杂。
  • 这是 PyQt5,Qt Designer 是它的可视化实现,因此您可以拖放按钮。
  • 也许不清楚,但我本质上是在问如何在 PyQt 中做到这一点。
  • 您可以将原始 Qt Designer .ui 文件传输到 .py 文件,而不是使用 Qt 生成的 cpp 文件。python pyuic.py -o pathto/Pyfile pathto/Uifile如果使用 pyqt 你应该有pyuic

标签: python c++ qt qt-designer pyuic


【解决方案1】:

我不知道你为什么需要 C++,你可以在 python 中做你想做的事。在 QT Designer 中设计您的 UI。我喜欢避免使用pyuic,我更喜欢使用以下方式,也许你会发现它更好。假设您的 UI 文件名为 something.ui,并且您在 QT Designer 中将按钮命名为 pushButton_2,那么 python 中的代码将是:

from PyQt4 import QtCore, QtGui, uic
Ui_somewindow, _ = uic.loadUiType("something.ui") #the path to your UI

class SomeWindow(QtGui.QMainWindow, Ui_somewindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_somewindow.__init__(self)
        self.setupUi(self)
        self.pushButton_2.clicked.connect(self.yourFunction)

   def yourFunction(self):
        #the function you imported or anything you want to happen when the button is clicked.

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = SomeWindow()
    window.show()
    sys.exit(app.exec_())

希望这会有所帮助!

【讨论】:

  • 这是一个与我预期不同的工作流程,但这是我正在寻找的确切答案,谢谢!
猜你喜欢
  • 2017-02-21
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
  • 2019-06-12
  • 2011-03-21
  • 1970-01-01
相关资源
最近更新 更多