Eric6与pyqt5学习笔记 8【菜单栏如何添加点击事件,跳转URL】

时间:2021-02-21 23:01:55

首先介绍,按钮如何实现跳转外部链接

# -*-coding:utf-8-*-
# @Author : "GETF"
# @Time : 2018/3/1 13:12

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton,QDesktopWidget,QLabel,QGridLayout
import webbrowser,sys


class Ui_MainWindow(QWidget):
    item_name = "PyQt打开外部链接"

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

    def initUI(self):
        self.tips_1 = QLabel("网站:<a href='http://blog.csdn.net/column/details/18112.html'>http://blog.csdn.net/column/details/18112.html</a>");
        self.tips_1.setOpenExternalLinks(True)

        self.btn_webbrowser = QPushButton('webbrowser效果', self)

        self.btn_webbrowser.clicked.connect(self.btn_webbrowser_Clicked)

        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(self.btn_webbrowser, 1, 0)
        grid.addWidget(self.tips_1, 2, 0)

        self.setLayout(grid)

        self.resize(250, 150)
        self.setMinimumSize(266, 304);
        self.setMaximumSize(266, 304);
        self.center()
        self.setWindowTitle(self.item_name)
        self.show()


    def btn_webbrowser_Clicked(self):
        webbrowser.open('http://blog.csdn.net/column/details/18112.html')


    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    a = Ui_MainWindow()
    sys.exit(app.exec_())

而菜单栏如何实现呢,这里利用到了事件triggered.connect
参考问题及回答,点这里
菜单栏单纯的menu尚未实现如何直接利用点击事件,等待之后详细阅读官方文档再补充,直接可以通过二级菜单实现,举例如下:

self.menuAbout = QtWidgets.QMenu(self.menuBar)
self.menuAbout.setObjectName("menuAbout")

self.actionabout = QtWidgets.QAction(MainWindow)
self.actionabout.setCheckable(False)
self.actionabout.setObjectName("actionabout")
self.actionabout.triggered.connect(self.About_webbrowser_Clicked)


self.actionabout.setText(_translate("MainWindow", "关于(a)"))
self.actionabout.setStatusTip(_translate("MainWindow", "了解我们"))


def About_webbrowser_Clicked(self):
webbrowser.open('http://blog.csdn.net/column/details/18112.html')