【问题标题】:Connecting Push Button to function on different tab using PyQt5使用 PyQt5 将按钮连接到不同选项卡上的功能
【发布时间】:2021-12-15 01:43:21
【问题描述】:

我正在尝试将按钮连接到不同选项卡上的功能,我一直在寻找解决方案但无法取得任何进展,我在下面包含了代码的简化版本。基本上,我希望 Tab1 上的 QPushButton 连接到 Tab2 上的 plot_show 函数。任何建议将不胜感激。

谢谢。

import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvas
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc


class  Tab1(qtw.QWidget):
    def __init__(self):
        super().__init__()
        
        self.resize(1000,850)
        self.button1 = qtw.QPushButton("Plot")
        
        #self.button1.clicked.connect(??????)????? # connect this to the plot_show function on Tab2
        
        main_layout = qtw.QHBoxLayout()
        self.setLayout(main_layout)
        main_layout.addWidget(self.button1)

class Tab2(qtw.QWidget):
    def __init__(self):
        super().__init__()
        
        self.x=[1,2,3]
        self.y=[4,5,6]

        self.fig, self.ax = plt.subplots()
        self.plotWidget=FigureCanvas(self.fig)
            
        main_layout = qtw.QVBoxLayout()
        self.setLayout(main_layout)
        main_layout.addWidget(self.plotWidget)

    def plot_show(self):
        self.ax.plot(self.x,self.y)

class MainWindow(qtw.QMainWindow):

    def __init__(self):
        super().__init__()
        
        self.tabs = qtw.QTabWidget()
        self.setCentralWidget(self.tabs)

        self.tab1=Tab1()
        self.tab2=Tab2()
        self.tabs.addTab(self.tab1, "Tab 1")
        self.tabs.addTab(self.tab2, "Tab 2")

        self.show()

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    mw = MainWindow()
    sys.exit(app.exec())

【问题讨论】:

  • MainWindow.__init__ 中建立连接,您可以在其中引用两个选项卡。

标签: pyqt pyqt5


【解决方案1】:

好的,根据您的代码,我做了一个快速修复来实现您的要求,只需将 self.tab1.button1.clicked.connect(self.tab2.plot_show) 放入您的 MainWindow 类中:

class MainWindow(qtw.QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.tabs = qtw.QTabWidget()
        self.setCentralWidget(self.tabs)

        self.tab1 = Tab1()
        self.tab2 = Tab2()
        self.tabs.addTab(self.tab1, "Tab 1")
        self.tabs.addTab(self.tab2, "Tab 2")

        self.tab1.button1.clicked.connect(self.tab2.plot_show)
        self.show()

单击按钮,更改选项卡,您的绘图位于 tab2 中。因此,您必须从像 MainWindow 这样的公共位置进行连接,或者使用继承原则。我希望这可以作为您代码的开始。

另外请注意,您不需要为添加到 QTabsWidget 的选项卡创建新类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2014-07-10
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多