在qtreewidget pyqt5中格式化子项

时间:2018-10-07 20:09:36

标签: python pyqt pyqt5

from __future__ import print_function
import socket
from struct import unpack
import Queue
from PIL import Image


HOST = '10.0.0.2'
PORT = 12345
BUFSIZE = 4096
q = Queue.Queue()

class Receiver:
    ''' Buffer binary data from socket conn '''
    def __init__(self, conn):
        self.conn = conn
        self.buff = bytearray()

    def get(self, size):
        ''' Get size bytes from the buffer, reading
            from conn when necessary 
        '''
        while len(self.buff) < size:
            data = self.conn.recv(BUFSIZE)
            if not data:
                break
            self.buff.extend(data)
        # Extract the desired bytes
        result = self.buff[:size]
        # and remove them from the buffer
        del self.buff[:size]
        return bytes(result)

    def save(self, fname):
        ''' Save the remaining bytes to file fname '''
        with open(fname, 'wb') as f:
            if self.buff:
                f.write(bytes(self.buff))
            while True:
                data = self.conn.recv(BUFSIZE)
                if not data:
                    break
                f.write(data)


def processP(q):
    i = 0
    while not q.empty():
        name = q.get()
        col = Image.open(name)
        gray = col.convert('L')
        bw = gray.point(lambda x: 0 if x<128 else 255, '1')
        bw.save("%d+30.jpg" % (i))
        i = i + 1
    #UDP_IP = "10.0.0.3"
    #UDP_PORT = 5005
    #MESSAGE = "Hello, World!"
    #print("UDP target IP:", UDP_IP)
    #print("UDP target port:", UDP_PORT)
    #print("message:", MESSAGE)
    #sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
    #sock2.sendto(MESSAGE, (UDP_IP, UDP_PORT))


def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        sock.bind((HOST, PORT))
    except socket.error as err:
        print('Bind failed', err)
        return
    sock.listen(1)
    print('Socket now listening at', HOST, PORT)
    try:
        while True:
            conn, addr = sock.accept()
            print('Connected with', *addr)
            # Create a buffer for this connection
            receiver = Receiver(conn)
            # Get the length of the file name
            name_size = unpack('B', receiver.get(1))[0] 
            # Get the file name itself
            name = receiver.get(name_size).decode()
            q.put(name)
            print('name', name)
            # Save the file
            receiver.save(name)
            conn.close()
            print('saved\n')
            if (name == "sample.jpg"):
                print('------------ok-------------')
                processP(q)

    # Hit Break / Ctrl-C to exit
    except KeyboardInterrupt:
        print('\nClosing')

    sock.close()

if __name__ == '__main__':
    main()

在这里,我在STYLESHEET中将高度设置为80px。但我想将高度设置为40px(用于子项)和80px(用于toplevelitem)。我怎么做? 预先感谢

1 个答案:

答案 0 :(得分:1)

Qt样式表是通用的,对于QTreeWidget,没有选择器可以区分父母和孩子,因此另一个选择是使用委托,如下所示:

from PyQt5 import QtCore, QtWidgets

STYLESHEET = '''QTreeWidget {border:None} 
    QTreeWidget::Item{
        border-bottom:2px solid black;
        color: rgba(255,255,255,255);
    }
    QTreeView{
        alternate-background-color: rgba(170,170,170,255);
        background: rgba(211,211,211,255);
    }'''


class StyledItemDelegate(QtWidgets.QStyledItemDelegate):
    def sizeHint(self, option, index):
        s = super(StyledItemDelegate, self).sizeHint(option, index)
        if index.parent().isValid():
            s.setHeight(40)
        else:
            s.setHeight(80)
        return s


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.treeWidget = QtWidgets.QTreeWidget()
        delegate = StyledItemDelegate(self.treeWidget)
        self.treeWidget.setItemDelegate(delegate)
        self.treeWidget.setAlternatingRowColors(True)
        self.treeWidget.setStyleSheet(STYLESHEET)
        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.treeWidget)
        for i in range(5):
            it = QtWidgets.QTreeWidgetItem(["parent {}".format(i)])
            self.treeWidget.addTopLevelItem(it)
            for j in range(5):
                child = QtWidgets.QTreeWidgetItem(["children {}{}".format(i, j)])
                it.addChild(child)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

enter image description here