Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pythonでjsonファイルを読み書き
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- mode: python;Encoding: utf8n -*-
"""
PyQt + FontDialog + json のテスト
ラベルのフォントを、
フォント選択ダイアログで選択したフォントに変更して、
フォント種類をjsonファイルに記録する。
英数字のフォント名も、日本語フォント名も、jsonファイルに記録できる。
"""
import os
import sys
from PyQt4 import QtGui
import codecs
import json
JSON_FILE = "settings_font.json"
DEF_STR = "The quick brown fox jumps over a lazy dog.\n" \
u"いろはにほへと ちりぬるを"
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
"""UIの初期化"""
vbox = QtGui.QVBoxLayout()
btn = QtGui.QPushButton('Dialog', self)
btn.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
btn.move(20, 20)
vbox.addWidget(btn)
btn.clicked.connect(self.showDialog)
self.lbl = QtGui.QLabel(DEF_STR, self)
self.lbl.move(130, 20)
vbox.addWidget(self.lbl)
self.lbl2 = QtGui.QLabel("", self)
self.lbl2.move(130, 60)
vbox.addWidget(self.lbl2)
self.setLayout(vbox)
self.setGeometry(300, 300, 250, 180)
self.setWindowTitle('Font dialog')
self.show()
# open json file
self.json_path = os.path.join(os.path.dirname(__file__), JSON_FILE)
self.json_dic = self.read_json(self.json_path)
# 前回終了時のフォント種類が記録されていたら再現する
font = self.get_font_from_json(self.json_dic)
if font is None:
print "font is None"
else:
self.lbl.setFont(font)
def showDialog(self):
"""フォント選択ダイアログの表示"""
font, ok = QtGui.QFontDialog.getFont(self.lbl.font())
if ok:
self.lbl.setFont(font) # Widgetのフォントを変更
font_name = unicode(font.toString())
self.lbl2.setText(font_name)
# JSON用辞書に記録
self.set_font_to_json(font)
self.write_json(self.json_path, self.json_dic)
def set_font_to_json(self, font):
"""json用辞書にフォント種類を記録"""
self.json_dic['fontrawname'] = unicode(font.rawName())
self.json_dic['fontpointsize'] = font.pointSize()
self.json_dic['fontweight'] = font.weight()
self.json_dic['fontitalic'] = 1 if font.italic() else 0
self.json_dic['fontfixed'] = 1 if font.fixedPitch() else 0
self.json_dic['fontpointsizef'] = font.pointSizeF()
def get_font_from_json(self, json_dic):
"""json用辞書を元にフォント種類を取得"""
if 'fontrawname' in json_dic:
rawname = json_dic['fontrawname']
if rawname == "":
return None
else:
font = QtGui.QFont(rawname)
if 'fontweight' in json_dic:
font.setWeight(json_dic['fontweight'])
if 'fontpointsize' in json_dic:
font.setPointSize(json_dic['fontpointsize'])
if 'fontitalic' in json_dic:
fg = True if json_dic['fontitalic'] == 1 else False
font.setItalic(fg)
if 'fontfixed' in json_dic:
fg = True if json_dic['fontfixed'] == 1 else False
font.setFixedPitch(fg)
return font
else:
return None
def read_json(self, json_path):
"""jsonの読み込み"""
json_dic = {}
fg = False
if os.path.exists(json_path):
with codecs.open(json_path, 'r', 'utf8') as f:
try:
json_dic = json.load(f)
fg = True
except IOError, inst:
sys.stderr.write(str(inst) + "\n")
if fg:
return json_dic
# jsonが読み込めないので初期化と保存をする
json_dic = {'fontrawname': ''}
self.write_json(json_path, json_dic)
return json_dic
def write_json(self, json_path, json_dic):
"""jsonの保存"""
fg = False
with codecs.open(json_path, 'w', 'utf8') as f:
try:
json.dump(json_dic, f, ensure_ascii=False,
sort_keys=True, indent=4)
fg = True
except IOError, inst:
sys.stderr.write(str(inst) + "\n")
self.dump_json_file(json_path)
return fg
def dump_json_file(self, json_path):
"""jsonファイルの内容をダンプ"""
with codecs.open(json_path, 'r', 'utf8') as f:
try:
print f.read()
except IOError, inst:
sys.stderr.write(str(inst) + "\n")
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.