PyQt How to Create a Custom QWidget

  • 2021-10-13 07:54:11
  • OfStack

Directory Development Environment Main Files: main.pyapp_main_window. pyTips
Multiple controls can exist in list
QApplication and QWidget
Note the problem of widget holding external object references

Development environment

Win7 PyCharm Python3.5.1 PyQt5

Main documents:


|-- main.py
|-- res
| `-- fish.jpg
`-- ui
 `-- app_widget.py

main.py


import sys

from PyQt5.QtWidgets import QApplication

from ui.app_widget import AppQWidget

if __name__ == '__main__':
 app = QApplication(sys.argv)
 w = AppQWidget()
 w.show()

 sys.exit(app.exec_())

app_main_window.py

Customized a window with a center display, and the confirmation box will pop up when it is closed


from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets 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):
  # self.setGeometry(300, 300, 400, 200) #  Equivalent to move And resize
  self.resize(300, 200)
  self.move_to_center()
  self.setWindowTitle('Demo1')
  self.setWindowIcon(QIcon('res/fish.jpg'))

  btn1 = QPushButton('Quit', self)
  btn1.setToolTip('Click to quit')
  btn1.resize(btn1.sizeHint())
  btn1.move(200, 150)
  btn1.clicked.connect(QCoreApplication.instance().quit) # cannot locate function connect

 def closeEvent(self, event):
  reply = QMessageBox.question(self, 'Message',
          'Are you sure to quit now?',
          QMessageBox.Yes | QMessageBox.No,
          QMessageBox.No)
  if reply == QMessageBox.Yes:
   event.accept()
  else:
   event.ignore()

 def move_to_center(self):
  qr = self.frameGeometry()
  cp = QDesktopWidget().availableGeometry().center() # got center info here
  qr.moveCenter(cp)
  self.move(qr.topLeft()) #  Apply the top left point of the window to qr The point at the top left of the rectangle, so it is centered on our screen 

Tips

Multiple controls can exist in list

There is 1 case, and the list needs to be traversed directly when the whole operation is needed


 #  Controls in the same group can exist with the same 1 A list Medium 
 self.cb_list = [
  self.ma.i2cCB,
  self.ma.mipiCB,
  self.ma.eepromCB,
  self.ma.tem_sensorCB,
  self.ma.lensCB,
  self.ma.vcmCB,
  self.ma.mirrorCB,
  self.ma.mirrorCaliCB, ]

 self.test_count_et_list = [
  self.ma.i2cCountEt,
  self.ma.mipiCountEt,
  self.ma.eepromCountEt,
  self.ma.tem_sensorCountEt,
  self.ma.lensCountEt,
  self.ma.vcmCountEt,
  self.ma.mirrorCountEt,
  self.ma.mirrorCaliCountEt,
 ]

#  When you need to manipulate a group of controls   Traverse the list directly 
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 & cb.isChecked()
 self.ma.selecteAllCB.setChecked(choose_all)

QApplication and QWidget

QApplication is a singleton. In QWidget, objects can be obtained through QApplication. instance ()

In fact, using QtGui. QWidget () before instantiating QApplication will report an error


>>> QtGui.QWidget()
QWidget: Must construct a QApplication before a QPaintDevice

Refer to How QApplication () and QWidget () objects are connected in PySide/PyQt?

In our custom QMainWindow, we can also get the instance of QApplication directly.


class RustMainWindow(QMainWindow):
 """ This is the main class """

 def _trigger_english(self):
  print "Change to English", QApplication.instance()

# Change to English <PyQt4.QtGui.QApplication object at 0x02ABE3A0>

Note the problem of widget holding external object references

If the reference is handed to widget at the place where the program starts, the exit will cause the application to fail to close (similar to memory leakage).


if __name__ == '__main__':
 app = QApplication(sys.argv)
 #  Put it here app Hand over to MainWindow , MainWindow You can't exit the application normally when you close it 
 main_d = RustMainWindow(app) #  This is not recommended 
 main_d.show()
 sys.exit(app.exec_())

These are the details of how PyQt creates a custom QWidget. For more information about PyQt creating a custom QWidget, please pay attention to other related articles on this site!


Related articles: