LoginSignup
3
4

More than 1 year has passed since last update.

PyQt5で、画面Aから画面Bを複数のウィンドウに出力する

Last updated at Posted at 2018-07-26

画面A
無題.png

ボタンをクリックすると、画面Bに選んだコーヒーの特徴が出ます。
すると、画面Bを複数表示し、比較したくなりますよね。

ですが、ネット上にあるサンプルだと画面Bを一つしか出力できません。
いろいろ考えた結果、以下のようにすると複数出力できました。

coffee.py
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, QLabel
import coffeeInfo


class App(QWidget):

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

        self.title = "aa"
        self.setWindowTitle(self.title)
        self.setGeometry(300, 300, 300, 150)

        self.ex_list = []

        self.init_ui()
        self.show()

    def init_ui(self):
        button1 = QPushButton('コーヒーA', self)
        button1.clicked.connect(self.on_click)

        button2 = QPushButton('コーヒーB', self)
        button2.clicked.connect(self.on_click)

        button3 = QPushButton('コーヒーC', self)
        button3.clicked.connect(self.on_click)

        label = QLabel("好きなコーヒーを選んでください", self)

        hbox = QHBoxLayout()
        hbox.addWidget(button1)
        hbox.addWidget(button2)
        hbox.addWidget(button3)

        vbox = QVBoxLayout()
        vbox.addWidget(label)
        vbox.addLayout(hbox)

        self.setLayout(vbox)

    def on_click(self):
        button = self.sender()
        self.ex_list.append(coffeeInfo.App(button.text()))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
coffeeInfo.py
from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout


class App(QWidget):

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

        self.title = select
        self.setWindowTitle(self.title)
        self.setGeometry(650, 200, 300, 150)

        self.select = select

        self.ex_list = []

        self.init_ui()
        self.show()

    def init_ui(self):

        info = {"コーヒーA": "まったりとして、それでいてしつこくない",
                "コーヒーB": "アラビカとかロブスタですね",
                "コーヒーC": "女だ……女がいる!!!!"}

        label = QLabel(info[self.select], self)

        vbox = QVBoxLayout()
        vbox.addWidget(label)
        self.setLayout(vbox)

変えたところ

(前)self.ex = coffeeInfo.AppApp()
(後)self.ex_list.append(coffeeInfo.App())

リストに変更しています。

説明ッ!

self.ex = coffeeInfo.App() は、Appクラスのオブジェクトを生成し、exという変数に入れています。
これだと、self.exには一つのオブジェクトしか入らないので、画面も一つしか作れません。

self.ex_list.append(coffeeInfo.App()) とすると、

  • 最初に出力される画面Bは self.ex_list[0]
  • つぎに出力される画面Bは self.ex_list[1]
  • つぎに出力される画面Bは self.ex_list[2]

と、別の変数に入るので、複数の画面が出力されます。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4