简体   繁体   中英

Font Dialog in PyQt4

I'm writing a small application using PyQt4. I need to change font of a html file so how can I pick font name from the list of installed fonts? I have a tool button in my main window that is connected to a function as below but each time I run my program, instead of my main window, the font dialog is appear:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        ...        
        QtCore.QObject.connect(self.toolButton, QtCore.SIGNAL("clicked()"), self.fontPicker())
        ...

    def fontPicker(self):
        f, ok = QtGui.QFontDialog.getFont()
        if ok:
            ...

def main(dir_in):
    app = QtGui.QApplication(sys.argv)
    form = QtGui.QMainWindow()
    myapp = Ui_MainWindow()
    myapp.setupUi(form)
    form.show()
    sys.exit(app.exec_())

I think that your code will be used, when you want to define Widgets, Layouts in another class. For example:

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

# In the class Ui_SideWindow you can define widgets, signals, slots, ect.
class Ui_SideWindow(object):
    def setupUi(self, MainWindow):
        self.label_sidewindow = QLabel()
        self.label_sidewindow.setText("I am defined in another class!")

# The class "Mainwindow" inherit the defined widgets, ect. from Ui_SideWindow,
# if you add the class in the definition, so class name(BaseClassName)      
class MainWindow(QMainWindow, Ui_SideWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # call setupUI
        self.setupUi(self)

        self.setWindowTitle("Get Font") 

        self.button = QPushButton()
        self.button.setText(" Get Font")

        self.label = QLabel()

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.button)
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.label_sidewindow) # defined in class Ui_SideWindow            
        self.main_frame = QWidget()
        self.main_frame.setLayout(self.layout)

        self.setCentralWidget(self.main_frame)  

        #####################
        # Signals and Slots #
        #####################

        self.connect(self.button, SIGNAL("clicked()"), self.getfont)

    def getfont(self):

        item, ok = QFontDialog.getFont()

        if ok is True:
            self.label.setText(item.toString())
        else:
            pass


def main():
    app = QApplication(sys.argv)
    form = MainWindow()
    form.show()

    app.exec_()


if __name__ == "__main__":
    main()

I hope I could help you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM