development environment (computer)
Win7 PyCharm Python3.5.1 PyQt5
Main Document:
|-- |-- res | `-- `-- ui `-- app_widget.py
import sys from import QApplication from ui.app_widget import AppQWidget if __name__ == '__main__': app = QApplication() w = AppQWidget() () (app.exec_())
app_main_window.py
Customized a centered window that pops up a confirmation box when closed
from import QCoreApplication from import QIcon from import QWidget, QPushButton, QDesktopWidget, QMessageBox class AppQWidget(QWidget): """ A custom QWidget by Rust Fisher """ def __init__(self): super().__init__() self.init_ui() def init_ui(self): # (300, 300, 400, 200) # Equivalent to move and resize (300, 200) self.move_to_center() ('Demo1') (QIcon('res/')) btn1 = QPushButton('Quit', self) ('Click to quit') (()) (200, 150) (().quit) # cannot locate function connect def closeEvent(self, event): reply = (self, 'Message', 'Are you sure to quit now?', | , ) if reply == : () else: () def move_to_center(self): qr = () cp = QDesktopWidget().availableGeometry().center() # got center info here (cp) (()) # The point in the upper left of the application window to theqrThe point at the top left of the rectangle,So centered on our screen
Tips
Multiple controls can exist in a list
exist together, and traverse the list directly when you need to manipulate the whole.
# Controls in the same group can exist in the same list self.cb_list = [ .i2cCB, , , .tem_sensorCB, , , , , ] self.test_count_et_list = [ .i2cCountEt, , , .tem_sensorCountEt, , , , , ] # When you need to manipulate a group of controls, just traverse the list. def _click_test_item_cb(self): """ Update [choose all checkbox] by all test item state """ choose_all = True for cb in self.cb_list: choose_all = choose_all & () (choose_all)
QApplication and QWidget
QApplication is a singleton, and in QWidget you can get the object via ()
Actually using () before instantiating the QApplication is going to report an error
>>> () QWidget: Must construct a QApplication before a QPaintDevice
consultationHow QApplication() and QWidget() objects are connected in PySide/PyQt?
It is also possible to get an instance of QApplication directly in our custom QMainWindow.
class RustMainWindow(QMainWindow): """ This is the main class """ def _trigger_english(self): print "Change to English", () # Change to English < object at 0x02ABE3A0>
Note that widgets hold references to external objects
If the reference is given to the widget where the program is started, exiting will cause a problem where the application cannot be closed (similar to a memory leak).
if __name__ == '__main__': app = QApplication() # Here the app is given to the MainWindow, and it is not possible to exit the app properly when the MainWindow is closed main_d = RustMainWindow(app) # It's not recommended main_d.show() (app.exec_())
Above is how to create a custom QWidget PyQt details, more information about PyQt create a custom QWidget please focus on my other related articles!