python3+PyQt5 使用三种不同的简便项窗口部件显示数据的方法

本文通过将同一个数据集在三种不同的简便项窗口部件中显示。三个窗口的数据得到实时的同步,数据和视图分离。当添加或删除数据行,三个不同的视图均保持同步。数据将保存在本地文件中,而非数据库。对于小型和临时性数据集来说,这些简便窗口部件非常有用,可以用在非单独数据集中-数据自身的显示,编辑和存储。

所使用的数据集:

/home/yrd/eric_workspace/chap14/ships_conv/ships.py

#!/usr/bin/env python3

import platform
from PyQt5.QtCore import QDataStream, QFile,QIODevice,Qt
from PyQt5.QtWidgets import QApplication
NAME, OWNER, COUNTRY, DESCRIPTION, TEU = range(5)

MAGIC_NUMBER = 0x570C4
FILE_VERSION = 1

class Ship(object):

  def __init__(self, name, owner, country, teu=0, description=""):
    self.name = name
    self.owner = owner
    self.country = country
    self.teu = teu
    self.description = description

  def __hash__(self):
    return super(Ship, self).__hash__()

  def __lt__(self, other):
    return bool(self.name.lower()<other.name.lower())

  def __eq__(self, other):
    return bool(self.name.lower()==other.name.lower())

class ShipContainer(object):

  def __init__(self, filename=""):
    self.filename = filename
    self.dirty = False
    self.ships = {}
    self.owners = set()
    self.countries = set()

  def ship(self, identity):
    return self.ships.get(identity)

  def addShip(self, ship):
    self.ships[id(ship)] = ship
    self.owners.add(str(ship.owner))
    self.countries.add(str(ship.country))
    self.dirty = True

  def removeShip(self, ship):
    del self.ships[id(ship)]
    del ship
    self.dirty = True

  def __len__(self):
    return len(self.ships)

  def __iter__(self):
    for ship in self.ships.values():
      yield ship

  def inOrder(self):
    return sorted(self.ships.values())

  def inCountryOwnerOrder(self):
    return sorted(self.ships.values(),
           key=lambda x: (x.country, x.owner, x.name))

  def load(self):
    exception = None
    fh = None
    try:
      if not self.filename:
        raise IOError("no filename specified for loading")
      fh = QFile(self.filename)
      if not fh.open(QIODevice.ReadOnly):
        raise IOError(str(fh.errorString()))
      stream = QDataStream(fh)
      magic = stream.readInt32()
      if magic != MAGIC_NUMBER:
        raise IOError("unrecognized file type")
      fileVersion = stream.readInt16()
      if fileVersion != FILE_VERSION:
        raise IOError("unrecognized file type version")
      self.ships = {}
      while not stream.atEnd():
        name = ""
        owner = ""
        country = ""
        description = ""
        name=stream.readQString()
        owner=stream.readQString()
        country=stream.readQString()
        description=stream.readQString()
        teu = stream.readInt32()
        ship = Ship(name, owner, country, teu, description)
        self.ships[id(ship)] = ship
        self.owners.add(str(owner))
        self.countries.add(str(country))
      self.dirty = False
    except IOError as e:
      exception = e
    finally:
      if fh is not None:
        fh.close()
      if exception is not None:
        raise exception

  def save(self):
    exception = None
    fh = None
    try:
      if not self.filename:
        raise IOError("no filename specified for saving")
      fh = QFile(self.filename)
      if not fh.open(QIODevice.WriteOnly):
        raise IOError(str(fh.errorString()))
      stream = QDataStream(fh)
      stream.writeInt32(MAGIC_NUMBER)
      stream.writeInt16(FILE_VERSION)
      stream.setVersion(QDataStream.Qt_5_7)
      for ship in self.ships.values():
        stream.writeQString(ship.name)
        stream.writeQString(ship.owner)
        stream.writeQString(ship.country)
        stream.writeQString(ship.description)
        stream.writeInt32(ship.teu)
      self.dirty = False
    except IOError as e:
      exception = e
    finally:
      if fh is not None:
        fh.close()
      if exception is not None:
        raise exception

def generateFakeShips():
  for name, owner, country, teu, description in (
("Emma M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 151687,
 "<b>W\u00E4rtsil\u00E4-Sulzer RTA96-C</b> main engine,"
 "<font color=green>109,000 hp</font>"),
("MSC Pamela", "MSC", "Liberia", 90449,
 "Draft <font color=green>15m</font>"),
("Colombo Express", "Hapag-Lloyd", "Germany", 93750,
 "Main engine, <font color=green>93,500 hp</font>"),
("Houston Express", "Norddeutsche Reederei", "Germany", 95000,
 "Features a <u>twisted leading edge full spade rudder</u>. "
 "Sister of <i>Savannah Express</i>"),
("Savannah Express", "Norddeutsche Reederei", "Germany", 95000,
 "Sister of <i>Houston Express</i>"),
("MSC Susanna", "MSC", "Liberia", 90449, ""),
("Eleonora M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 151687,
 "Captain <i>Hallam</i>"),
("Estelle M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 151687,
 "Captain <i>Wells</i>"),
("Evelyn M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 151687,
 "Captain <i>Byrne</i>"),
("Georg M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 97933, ""),
("Gerd M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 97933, ""),
("Gjertrud M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 97933, ""),
("Grete M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 97933, ""),
("Gudrun M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 97933, ""),
("Gunvor M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 97933, ""),
("CSCL Le Havre", "Danaos Shipping", "Cyprus", 107200, ""),
("CSCL Pusan", "Danaos Shipping", "Cyprus", 107200,
 "Captain <i>Watts</i>"),
("Xin Los Angeles", "China Shipping Container Lines (CSCL)",
 "Hong Kong", 107200, ""),
("Xin Shanghai", "China Shipping Container Lines (CSCL)", "Hong Kong",
 107200, ""),
("Cosco Beijing", "Costamare Shipping", "Greece", 99833, ""),
("Cosco Hellas", "Costamare Shipping", "Greece", 99833, ""),
("Cosco Guangzho", "Costamare Shipping", "Greece", 99833, ""),
("Cosco Ningbo", "Costamare Shipping", "Greece", 99833, ""),
("Cosco Yantian", "Costamare Shipping", "Greece", 99833, ""),
("CMA CGM Fidelio", "CMA CGM", "France", 99500, ""),
("CMA CGM Medea", "CMA CGM", "France", 95000, ""),
("CMA CGM Norma", "CMA CGM", "Bahamas", 95000, ""),
("CMA CGM Rigoletto", "CMA CGM", "France", 99500, ""),
("Arnold M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 93496,
 "Captain <i>Morrell</i>"),
("Anna M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 93496,
 "Captain <i>Lockhart</i>"),
("Albert M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 93496,
 "Captain <i>Tallow</i>"),
("Adrian M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 93496,
 "Captain <i>G. E. Ericson</i>"),
("Arthur M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 93496, ""),
("Axel M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 93496, ""),
("NYK Vega", "Nippon Yusen Kaisha", "Panama", 97825, ""),
("MSC Esthi", "MSC", "Liberia", 99500, ""),
("MSC Chicago", "Offen Claus-Peter", "Liberia", 90449, ""),
("MSC Bruxelles", "Offen Claus-Peter", "Liberia", 90449, ""),
("MSC Roma", "Offen Claus-Peter", "Liberia", 99500, ""),
("MSC Madeleine", "MSC", "Liberia", 107551, ""),
("MSC Ines", "MSC", "Liberia", 107551, ""),
("Hannover Bridge", "Kawasaki Kisen Kaisha", "Japan", 99500, ""),
("Charlotte M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Clementine M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Columbine M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Cornelia M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Chicago Express", "Hapag-Lloyd", "Germany", 93750, ""),
("Kyoto Express", "Hapag-Lloyd", "Germany", 93750, ""),
("Clifford M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Sally M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Sine M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Skagen M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Sofie M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Sor\u00F8 M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Sovereing M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Susan M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Svend M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Svendborg M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("A.P. M\u00F8ller", "M\u00E6rsk Line", "Denmark", 91690,
 "Captain <i>Ferraby</i>"),
("Caroline M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Carsten M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Chastine M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("Cornelius M\u00E6rsk", "M\u00E6rsk Line", "Denmark", 91690, ""),
("CMA CGM Otello", "CMA CGM", "France", 91400, ""),
("CMA CGM Tosca", "CMA CGM", "France", 91400, ""),
("CMA CGM Nabucco", "CMA CGM", "France", 91400, ""),
("CMA CGM La Traviata", "CMA CGM", "France", 91400, ""),
("CSCL Europe", "Danaos Shipping", "Cyprus", 90645, ""),
("CSCL Africa", "Seaspan Container Line", "Cyprus", 90645, ""),
("CSCL America", "Danaos Shipping ", "Cyprus", 90645, ""),
("CSCL Asia", "Seaspan Container Line", "Hong Kong", 90645, ""),
("CSCL Oceania", "Seaspan Container Line", "Hong Kong", 90645,
 "Captain <i>Baker</i>"),
("M\u00E6rsk Seville", "Blue Star GmbH", "Liberia", 94724, ""),
("M\u00E6rsk Santana", "Blue Star GmbH", "Liberia", 94724, ""),
("M\u00E6rsk Sheerness", "Blue Star GmbH", "Liberia", 94724, ""),
("M\u00E6rsk Sarnia", "Blue Star GmbH", "Liberia", 94724, ""),
("M\u00E6rsk Sydney", "Blue Star GmbH", "Liberia", 94724, ""),
("MSC Heidi", "MSC", "Panama", 95000, ""),
("MSC Rania", "MSC", "Panama", 95000, ""),
("MSC Silvana", "MSC", "Panama", 95000, ""),
("M\u00E6rsk Stralsund", "Blue Star GmbH", "Liberia", 95000, ""),
("M\u00E6rsk Saigon", "Blue Star GmbH", "Liberia", 95000, ""),
("M\u00E6rsk Seoul", "Blue Star Ship Managment GmbH", "Germany",
 95000, ""),
("M\u00E6rsk Surabaya", "Offen Claus-Peter", "Germany", 98400, ""),
("CMA CGM Hugo", "NSB Niederelbe", "Germany", 90745, ""),
("CMA CGM Vivaldi", "CMA CGM", "Bahamas", 90745, ""),
("MSC Rachele", "NSB Niederelbe", "Germany", 90745, ""),
("Pacific Link", "NSB Niederelbe", "Germany", 90745, ""),
("CMA CGM Carmen", "E R Schiffahrt", "Liberia", 89800, ""),
("CMA CGM Don Carlos", "E R Schiffahrt", "Liberia", 89800, ""),
("CMA CGM Don Giovanni", "E R Schiffahrt", "Liberia", 89800, ""),
("CMA CGM Parsifal", "E R Schiffahrt", "Liberia", 89800, ""),
("Cosco China", "E R Schiffahrt", "Liberia", 91649, ""),
("Cosco Germany", "E R Schiffahrt", "Liberia", 89800, ""),
("Cosco Napoli", "E R Schiffahrt", "Liberia", 89800, ""),
("YM Unison", "Yang Ming Line", "Taiwan", 88600, ""),
("YM Utmost", "Yang Ming Line", "Taiwan", 88600, ""),
("MSC Lucy", "MSC", "Panama", 89954, ""),
("MSC Maeva", "MSC", "Panama", 89954, ""),
("MSC Rita", "MSC", "Panama", 89954, ""),
("MSC Busan", "Offen Claus-Peter", "Panama", 89954, ""),
("MSC Beijing", "Offen Claus-Peter", "Panama", 89954, ""),
("MSC Toronto", "Offen Claus-Peter", "Panama", 89954, ""),
("MSC Charleston", "Offen Claus-Peter", "Panama", 89954, ""),
("MSC Vittoria", "MSC", "Panama", 89954, ""),
("Ever Champion", "NSB Niederelbe", "Marshall Islands", 90449,
 "Captain <i>Phillips</i>"),
("Ever Charming", "NSB Niederelbe", "Marshall Islands", 90449,
 "Captain <i>Tonbridge</i>"),
("Ever Chivalry", "NSB Niederelbe", "Marshall Islands", 90449, ""),
("Ever Conquest", "NSB Niederelbe", "Marshall Islands", 90449, ""),
("Ital Contessa", "NSB Niederelbe", "Marshall Islands", 90449, ""),
("Lt Cortesia", "NSB Niederelbe", "Marshall Islands", 90449, ""),
("OOCL Asia", "OOCL", "Hong Kong", 89097, ""),
("OOCL Atlanta", "OOCL", "Hong Kong", 89000, ""),
("OOCL Europe", "OOCL", "Hong Kong", 89097, ""),
("OOCL Hamburg", "OOCL", "Marshall Islands", 89097, ""),
("OOCL Long Beach", "OOCL", "Marshall Islands", 89097, ""),
("OOCL Ningbo", "OOCL", "Marshall Islands", 89097, ""),
("OOCL Shenzhen", "OOCL", "Hong Kong", 89097, ""),
("OOCL Tianjin", "OOCL", "Marshall Islands", 89097, ""),
("OOCL Tokyo", "OOCL", "Hong Kong", 89097, "")):
    yield Ship(name, owner, country, teu, description)

/home/yrd/eric_workspace/chap14/ships_conv/ships-dict.pyw

#!/usr/bin/env python3

import sys
from PyQt5.QtCore import QFile, QTimer, Qt
from PyQt5.QtWidgets import (QApplication, QDialog, QHBoxLayout, QLabel,
    QListWidget, QListWidgetItem, QMessageBox, QPushButton,
    QSplitter, QTableWidget, QTableWidgetItem, QTreeWidget,
    QTreeWidgetItem, QVBoxLayout, QWidget)
import ships

MAC = True
try:
  from PyQt5.QtGui import qt_mac_set_native_menubar
except ImportError:
  MAC = False

class MainForm(QDialog):

  def __init__(self, parent=None):
    super(MainForm, self).__init__(parent)

    listLabel = QLabel("&List")
    self.listWidget = QListWidget()
    listLabel.setBuddy(self.listWidget)

    tableLabel = QLabel("&Table")
    self.tableWidget = QTableWidget()
    tableLabel.setBuddy(self.tableWidget)

    treeLabel = QLabel("Tre&e")
    self.treeWidget = QTreeWidget()
    treeLabel.setBuddy(self.treeWidget)

    addShipButton = QPushButton("&Add Ship")
    removeShipButton = QPushButton("&Remove Ship")
    quitButton = QPushButton("&Quit")
    if not MAC:
      addShipButton.setFocusPolicy(Qt.NoFocus)
      removeShipButton.setFocusPolicy(Qt.NoFocus)
      quitButton.setFocusPolicy(Qt.NoFocus)

    splitter = QSplitter(Qt.Horizontal)
    vbox = QVBoxLayout()
    vbox.addWidget(listLabel)
    vbox.addWidget(self.listWidget)
    widget = QWidget()
    widget.setLayout(vbox)
    splitter.addWidget(widget)
    vbox = QVBoxLayout()
    vbox.addWidget(tableLabel)
    vbox.addWidget(self.tableWidget)
    widget = QWidget()
    widget.setLayout(vbox)
    splitter.addWidget(widget)
    vbox = QVBoxLayout()
    vbox.addWidget(treeLabel)
    vbox.addWidget(self.treeWidget)
    widget = QWidget()
    widget.setLayout(vbox)
    splitter.addWidget(widget)
    buttonLayout = QHBoxLayout()
    buttonLayout.addWidget(addShipButton)
    buttonLayout.addWidget(removeShipButton)
    buttonLayout.addStretch()
    buttonLayout.addWidget(quitButton)
    layout = QVBoxLayout()
    layout.addWidget(splitter)
    layout.addLayout(buttonLayout)
    self.setLayout(layout)

    self.tableWidget.itemChanged[QTableWidgetItem].connect(self.tableItemChanged)
    addShipButton.clicked.connect(self.addShip)
    removeShipButton.clicked.connect(self.removeShip)
    quitButton.clicked.connect(self.accept)

    self.ships = ships.ShipContainer("ships.dat")
    self.setWindowTitle("Ships (dict)")
    QTimer.singleShot(0, self.initialLoad)

  def initialLoad(self):
    if not QFile.exists(self.ships.filename):
      for ship in ships.generateFakeShips():
        self.ships.addShip(ship)
      self.ships.dirty = False
    else:
      try:
        self.ships.load()
      except IOError as e:
        QMessageBox.warning(self, "Ships - Error",
            "Failed to load: {0}".format(e))
    self.populateList()
    self.populateTable()
    self.tableWidget.sortItems(0)
    self.populateTree()

  def reject(self):
    self.accept()

  def accept(self):
    if (self.ships.dirty and
      QMessageBox.question(self, "Ships - Save?",
          "Save unsaved changes?",
          QMessageBox.Yes|QMessageBox.No) ==
          QMessageBox.Yes):
      try:
        self.ships.save()
      except IOError as e:
        QMessageBox.warning(self, "Ships - Error",
            "Failed to save: {0}".format(e))
    QDialog.accept(self)

  def populateList(self, selectedShip=None):
    selected = None
    self.listWidget.clear()
    for ship in self.ships.inOrder():
      item = QListWidgetItem("{0} of {1}/{2} ({3:,})".format(ship.name,ship.owner,ship.country,int(ship.teu)))
      self.listWidget.addItem(item)
      if selectedShip is not None and selectedShip == id(ship):
        selected = item
    if selected is not None:
      selected.setSelected(True)
      self.listWidget.setCurrentItem(selected)

  def populateTable(self, selectedShip=None):
    selected = None
    self.tableWidget.clear()
    self.tableWidget.setSortingEnabled(False)
    self.tableWidget.setRowCount(len(self.ships))
    headers = ["Name", "Owner", "Country", "Description", "TEU"]
    self.tableWidget.setColumnCount(len(headers))
    self.tableWidget.setHorizontalHeaderLabels(headers)
    for row, ship in enumerate(self.ships):
      item = QTableWidgetItem(ship.name)
      item.setData(Qt.UserRole, id(ship))
      if selectedShip is not None and selectedShip == id(ship):
        selected = item
      self.tableWidget.setItem(row, ships.NAME, item)
      self.tableWidget.setItem(row, ships.OWNER,
          QTableWidgetItem(ship.owner))
      self.tableWidget.setItem(row, ships.COUNTRY,
          QTableWidgetItem(ship.country))
      self.tableWidget.setItem(row, ships.DESCRIPTION,
          QTableWidgetItem(ship.description))
      item = QTableWidgetItem("{0:>8}".format(ship.teu))
      item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)
      self.tableWidget.setItem(row, ships.TEU, item)
    self.tableWidget.setSortingEnabled(True)
    self.tableWidget.resizeColumnsToContents()
    if selected is not None:
      selected.setSelected(True)
      self.tableWidget.setCurrentItem(selected)

  def populateTree(self, selectedShip=None):
    selected = None
    self.treeWidget.clear()
    self.treeWidget.setColumnCount(2)
    self.treeWidget.setHeaderLabels(["Country/Owner/Name", "TEU"])
    self.treeWidget.setItemsExpandable(True)
    parentFromCountry = {}
    parentFromCountryOwner = {}
    for ship in self.ships.inCountryOwnerOrder():
      ancestor = parentFromCountry.get(ship.country)
      if ancestor is None:
        ancestor = QTreeWidgetItem(self.treeWidget, [ship.country])
        parentFromCountry[ship.country] = ancestor
      countryowner = ship.country + "/" + ship.owner
      parent = parentFromCountryOwner.get(countryowner)
      if parent is None:
        parent = QTreeWidgetItem(ancestor, [ship.owner])
        parentFromCountryOwner[countryowner] = parent
      item = QTreeWidgetItem(parent, [ship.name,"{0}".format(ship.teu)])
      item.setTextAlignment(1, Qt.AlignRight|Qt.AlignVCenter)
      if selectedShip is not None and selectedShip == id(ship):
        selected = item
      self.treeWidget.expandItem(parent)
      self.treeWidget.expandItem(ancestor)
    self.treeWidget.resizeColumnToContents(0)
    self.treeWidget.resizeColumnToContents(1)
    if selected is not None:
      selected.setSelected(True)
      self.treeWidget.setCurrentItem(selected)
    print(parentFromCountry)
    print(parentFromCountryOwner)

  def addShip(self):
    ship = ships.Ship(" Unknown", " Unknown", " Unknown")
    self.ships.addShip(ship)
    self.populateList()
    self.populateTree()
    self.populateTable(id(ship))
    self.tableWidget.setFocus()
    self.tableWidget.editItem(self.tableWidget.currentItem())

  def tableItemChanged(self, item):
    ship = self.currentTableShip()
    if ship is None:
      return
    column = self.tableWidget.currentColumn()
    if column == ships.NAME:
      ship.name = item.text().strip()
    elif column == ships.OWNER:
      ship.owner = item.text().strip()
    elif column == ships.COUNTRY:
      ship.country = item.text().strip()
    elif column == ships.DESCRIPTION:
      ship.description = item.text().strip()
    elif column == ships.TEU:
      ship.teu = item.text()
    self.ships.dirty = True
    self.populateList()
    self.populateTree()

  def currentTableShip(self):
    item = self.tableWidget.item(self.tableWidget.currentRow(), 0)
    if item is None:
      return None
    return self.ships.ship(
        item.data(Qt.UserRole))

  def removeShip(self):
    ship = self.currentTableShip()
    if ship is None:
      return
    if (QMessageBox.question(self, "Ships - Remove",
        "Remove {0} of {1}/{2}?".format(ship.name,ship.owner,ship.country),
        QMessageBox.Yes|QMessageBox.No) ==
        QMessageBox.No):
      return
    self.ships.removeShip(ship)
    self.populateList()
    self.populateTree()
    self.populateTable()

app = QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()

运行结果:

以上这篇python3+PyQt5 使用三种不同的简便项窗口部件显示数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • python3+PyQt5实现自定义流体混合窗口部件

    本文通过Python3+PyQt5实现自定义部件–流体混合窗口部件.通过逻辑(窗口)坐标绘制而成.调用setWindow,所有的绘制工作都会根据逻辑坐标系发生. #!/usr/bin/env python3 from PyQt5.QtCore import (QPointF, QSize, Qt,pyqtSignal) from PyQt5.QtWidgets import (QApplication, QFrame, QLabel, QSizePolicy, QSpinBox, QWidget

  • python3+PyQt5+Qt Designer实现堆叠窗口部件

    本文是对<Python Qt GUI快速编程>的第9章的堆叠窗口例子Vehicle Rental用Python3+PyQt5+Qt Designer进行改写. 第一部分无借用Qt Designer,完全用代码实现. 第二部分则借用Qt Designer,快速实现. 第一部分: import sys from PyQt5.QtCore import (Qt) from PyQt5.QtWidgets import (QApplication, QComboBox, QDialog, QDialo

  • python3+PyQt5实现自定义窗口部件Counters

    本文通过Python3+PyQt5实现自定义部件–Counters自定 窗口部件.这个窗口是3*3的网格.本文有两个例子如下: /home/yrd/eric_workspace/chap11/counters.py. /home/yrd/eric_workspace/chap11/counters_dnd.py 第二个例子在第一个例子的基础上实现能通过鼠标拖拽球到不同的网格中. /home/yrd/eric_workspace/chap11/counters.py #!/usr/bin/env

  • python3+PyQt5使用数据库窗口视图

    能够为数据库数据提供的最简单的用户界面之一就是窗体,窗体可以一次性呈现出来自同一记录的各个域.本文通过python3+pyqt5改写实现了python Qt gui 快速变成15章的例子. #!/usr/bin/env python3 import os import sys from PyQt5.QtCore import (QDate, QDateTime, QFile, QVariant, Qt) from PyQt5.QtWidgets import (QApplication, QDa

  • python3+PyQt5 使用三种不同的简便项窗口部件显示数据的方法

    本文通过将同一个数据集在三种不同的简便项窗口部件中显示.三个窗口的数据得到实时的同步,数据和视图分离.当添加或删除数据行,三个不同的视图均保持同步.数据将保存在本地文件中,而非数据库.对于小型和临时性数据集来说,这些简便窗口部件非常有用,可以用在非单独数据集中-数据自身的显示,编辑和存储. 所使用的数据集: /home/yrd/eric_workspace/chap14/ships_conv/ships.py #!/usr/bin/env python3 import platform from

  • python3+PyQt5 自定义窗口部件--使用窗口部件样式表的方法

    本文借用HTML的css语法,将样式表应用到窗口部件.这里只是个简单的例子,实际上样式表的语法很丰富. 以下类似于css: StyleSheet = """ QComboBox { color: darkblue; } QLineEdit { color: darkgreen; } QLineEdit[mandatory="true"] { #mandatory="true"时,QLineEdit的样式会变化 background-co

  • 几种显示数据的方法的比较

    用于显示数据库数据的时候,一般用循环体来做,常用的方法有while()和for()两种语句,下面就来讲一下他们在不同情况下各自的用法. 我们来分别介绍: while()语句是可以显示全部数据,在不知道循环次数的情况下,尤其显得方便,而for()语句呢,可以输出显示从指定位置开始到指定位置结束的数据,在输出显示一定范围的数据时就用得上了.下面看一下编程实例: 我们先建一个数据库来备用:数据库名为:mydb 表名为:tbl. 用下面的语句:create table tal (idx int(3),u

  • Angularjs 自定义服务的三种方式(推荐)

    AngularJS简介: AngularJS 通过新的属性和表达式扩展了 HTML. AngularJS 可以构建一个单一页面应用程序(SPAs:Single Page Applications). AngularJS 学习起来非常简单. angularjs 中可通过三种($provider,$factory,$service)方式自定义服务,以下是不同的实现形式: // 定义module , module中注入$provide var starterApp = angular.module('

  • 关于C++中定义比较函数的三种方法小结

    C++编程优与Pascal的原因之一是C++中存在STL(标准模板库).STL存在很多有用的方法. C++模板库中的许多方法都需要相关参数有序,例如Sort().显然,如果你想对一个集合进行排序,你必须要知道集合中的对象,那个在前那个在后.因此,学会如何定义比较方法是非常重要的. C++模板库的许多容器需要相关类型有序,例如set<T> 和priority_queue<T>. 这篇文章旨在告诉大家如何为一个类定义一个排序方法,以便在STL容器或者方法中使用. 作为一个C++程序员,

  • Tensorflow 2.4加载处理图片的三种方式详解

    目录 前言 数据准备 使用内置函数读取并处理磁盘数据 自定义方式读取和处理磁盘数据 从网络上下载数据 前言 本文通过使用 cpu 版本的 tensorflow 2.4 ,介绍三种方式进行加载和预处理图片数据. 这里我们要确保 tensorflow 在 2.4 版本以上 ,python 在 3.8 版本以上,因为版本太低有些内置函数无法使用,然后要提前安装好 pillow 和 tensorflow_datasets ,方便进行后续的数据加载和处理工作. 由于本文不对模型进行质量保证,只介绍数据的加

  • Go高效率开发Web参数校验三种方式实例

    web开发中,你肯定见到过各种各样的表单或接口数据校验: 客户端参数校验:在数据提交到服务器之前,发生在浏览器端或者app应用端,相比服务器端校验,用户体验更好,能实时反馈用户的输入校验结果. 服务器端参数校验:发生在客户端提交数据并被服务器端程序接收之后,通常服务器端校验都是发生在将数据写入数据库之前,如果数据没通过校验,则会直接从服务器端返回错误消息,并且告诉客户端发生错误的具体位置和原因,服务器端校验不像客户端校验那样有好的用户体验,因为它直到整个表单都提交后才能返回错误信息.但是服务器端

  • 关于ZeroMQ 三种模式python3实现方式

    ZeroMQ是一个消息队列网络库,实现网络常用技术封装.在C/S中实现了三种模式,这段时间用python简单实现了一下,感觉python虽然灵活.但是数据处理不如C++自由灵活. Request-Reply模式: 客户端在请求后,服务端必须回响应 server: # -*-coding:utf-8 -*- import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:5555&qu

  • python3读取文件指定行的三种方法

    行遍历实现 在python中如果要将一个文件完全加载到内存中,通过file.readlines()即可,但是在文件占用较高时,我们是无法完整的将文件加载到内存中的,这时候就需要用到python的file.readline()进行迭代式的逐行读取: filename = 'hello.txt' with open(filename, 'r') as file: line = file.readline() counts = 1 while line: if counts >= 50000000:

  • python3 最常用的三种装饰器语法汇总

    目录 python3 最常用的三种装饰器语法总结 1.简述语法 2.不带参数的函数的装饰器 3.带参数的函数的装饰器 python3 最常用的三种装饰器语法总结 1.简述语法 装饰器也叫函数装饰器,主要作用是在不修改原来函数的代码情况下(函数本身不会被修改,执行方式也不变化),增加的一个"装饰"函数,把原来的函数当成一个整体,像传参一样给这个函数使用,并返回这个"函数".这个过程中我们增加一些函数相关的代码,当函数被执行的时候,就会一起执行,相当于让函数增加了更多的

随机推荐