「C MAGAZINE - Qt GUI プログラミング」のコード移植 第3章の前に(メニュー編)

参考にしている本はQt3を対象としているため、PyQt4ではQtのバージョンの違いを意識してコードを記述する必要がある。
ここではQt3からQt4にかけて大きく変わったメニューの作成方法を記載する。

Qt3でのメニュー

Qt3ではアクションを作成し、そのアクションを指定のポップアップメニューに追加する。
また、メニューバーに指定のポップアップメニューを追加する。
以下はPyQt3で記述したら、こうなるだろうと予想した内容の一部である。

        self.exitAct = QAction("E&xit", "Ctrl+Q", self)
        self.exitAct.setStatusTip("Exit the application")
        self.exitAct.activated.connect(qApp.quit)

        self.fileMenu = QPopupMenu(self)
        self.exitAct.addTo(self.fileMenu)

        self.menuBar().insertItem("&File", self.fileMenu)

Qt4でのメニュー

Qt4ではアクションを作成し、メニューバーにサブメニューを追加して、そのサブメニューにアクションを追加する。
以下はPyQt4で実際に動作するコードである。

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setWindowTitle("Menu Sample")

        self.exitAct = QAction("E&xit", self)
        self.exitAct.setShortcut(QKeySequence("Ctrl+Q"))
        self.exitAct.setStatusTip("Exit the application")
        self.exitAct.triggered.connect(qApp.quit)

        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.exitAct)

        self.central = QWidget(self)
        self.central.setStyleSheet("background-color: white")
        self.setCentralWidget(self.central)

        self.statusBar()

app = QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()