0

我是 python 的初学者,我想从一个简单的 GUI 开始。我使用 PyQt5 进行 gui 开发。

如果用户单击登录工具栏按钮,我想运行 itWorks()。这是我的代码:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
from PyQt5.QtGui import QIcon

class Main(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):               

        exitAct = QAction(QIcon('images/Login.ico'), 'Login', self)
        #exitAct.setShortcut('Ctrl+Q')
        exitAct.triggered.connect(qApp.quit)#why i cant run my function here?

        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAct)

        self.setGeometry(50, 50, 600, 600)
        self.setWindowTitle('Toolbar')    
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Main()
    sys.exit(app.exec_())

功能:

def itWorks():
   print("it works")

谢谢你的帮助

4

1 回答 1

0

我知道一年多以前就有人问过了,但我遇到了同样的问题并设法解决它。所以这里是创建“工具栏”并获取操作/事件的示例。

from PyQt5 import QtWidgets, QtGui, QtCore
import sys


class TestClass(QtWidgets.QMainWindow):
    """TestClass Implementation"""
    def __init__(self):
        super().__init__()
        self.resize(200, 100)

    def run(self):
        # Adding tool bar to the window
        toolBar = self.addToolBar("")

        # Creating Items for the tool-bar
        folderOpen = QtWidgets.QAction(QtGui.QIcon("add_pack.ico"), "Open Folder", toolBar)
        newDoc = QtWidgets.QAction("New Documents", toolBar)
        tools = QtWidgets.QAction("Tools", toolBar)

        # Adding those item into the tool-bar
        toolBar.addAction(folderOpen)
        toolBar.addAction(newDoc)
        toolBar.addAction(tools)

        # Setting the action/event on the entire tool-bar, setting a function to call to.
        toolBar.actionTriggered[QtWidgets.QAction].connect(self.whoGotSelected)
        self.show()

    def whoGotSelected(self, selection):
        # Getting the selected button obj, taking the given text name.
        name = selection.text()

        # Print the name selected.
        print(f"Tool-Bar |{name}| is selected")

if __name__ == '__main__': 
    app = QtWidgets.QApplication(sys.argv)
    test = TestClass()
    test.run()
    sys.exit(app.exec_())

输出是:

工具栏|打开文件夹| 被选中

工具栏 |新建文档| 被选中

工具栏 |工具| 被选中

这是它的样子

我添加了一个 .ico 只是为了使用示例,如果您在没有文件的情况下在系统上运行它,它会起作用,并且会显示一个空方块。

于 2019-07-11T05:44:24.100 回答