English 中文(简体)
换文书赢得一只字体,相当正确。
原标题:QTableView won t display single line of text quite right

随函附上:

import sys, logging, datetime

from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.Qt import QVBoxLayout

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.__class__.instance = self
        self.resize(1200, 1600) # w, h
        main_splitter = QtWidgets.QSplitter(self)
        main_splitter.setOrientation(QtCore.Qt.Vertical)
        self.setCentralWidget(main_splitter)
        self.top_frame = QtWidgets.QFrame()
        main_splitter.addWidget(self.top_frame)
        self.bottom_frame = BottomFrame()
        self.bottom_frame.setMaximumHeight(350)                
        self.bottom_frame.setMinimumHeight(100)
        main_splitter.addWidget(self.bottom_frame)
        main_splitter.setCollapsible(1, False)
        self.bottom_frame.construct()
            
class BottomFrame(QtWidgets.QFrame):
    def construct(self):
        layout = QtWidgets.QVBoxLayout(self)
        # without this you get the default 10 px border all round the table: too much
        layout.setContentsMargins(1, 1, 1, 1)
        self.setLayout(layout)
        self.messages_table = LogTableView()
        layout.addWidget(self.messages_table)
        self.messages_table.visual_log( hello world )                
        self.messages_table.visual_log( message 2 qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd  )
        self.messages_table.visual_log( message 3 )
        self.messages_table.visual_log( message 4 , logging.ERROR)
        self.messages_table.visual_log( message 5 )
        self.messages_table.visual_log( message 6 qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd qunaomdd  )
        self.messages_table.visual_log( message 7 )
        
class LogTableView(QtWidgets.QTableView):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setModel(QtGui.QStandardItemModel())
        self.horizontalHeader().setStretchLastSection(True)
        self.horizontalHeader().hide()
        self.setVerticalHeader(VerticalHeader(self))
        self.verticalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
        self.verticalHeader().hide()
        self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
        self.setAlternatingRowColors(True)
        # this doesn t seem to have any effect 
        # self.verticalHeader().setMinimumSectionSize(1)
        
    def sizeHintForRow(self, row ):
        hint = super().sizeHintForRow(row)
        # print(f size hint for row {row}: {hint} )
        # this doesn t seem to have any effect!
        if hint < 25 and hint > 10: 
            hint = 10
        return hint
        
    def visual_log(self, msg: str, log_level: int=logging.INFO):
        model = self.model()
        i_new_row = model.rowCount()
        model.insertRow(i_new_row)
        datetime_stamp_str = datetime.datetime.now().strftime( %a %H:%M:%S.%f )[:-3]
        model.setItem(i_new_row, 0, QtGui.QStandardItem(datetime_stamp_str))
        model.setItem(i_new_row, 1, QtGui.QStandardItem(str(log_level)))
        self.setColumnWidth(0, 160)
        self.setColumnWidth(1, 100)
        model.setItem(i_new_row, 2, QtGui.QStandardItem(msg))
        QtCore.QTimer.singleShot(0, self.resizeRowsToContents)
        QtCore.QTimer.singleShot(10, self.scrollToBottom)
            
class VerticalHeader(QtWidgets.QHeaderView):
    def __init__(self, parent):
        super().__init__(QtCore.Qt.Vertical, parent)
    
    def sectionSizeHint(self, logical_index):
        hint = super().sectionSizeHint(logical_index)
        print(f vh index {logical_index} hint {hint} )
        return hint

def main():
    app_instance = QtWidgets.QApplication(sys.argv)
    MainWindow().show()  
    sys.exit(app_instance.exec())
    
if __name__ ==  __main__ :
    main()

浏览高度为ALMOST。 我想要做的是:试图改造主要窗口:表格浏览量根据案文的实际高度(按需要调整)调整其高度。

BUT... 如果你有一部案文,需要一行以上,使增长高度正确,则单线浏览量总是稍微高。sizeHintForRow(),QTableView方法似乎总是将24(pixels)从超级阶级退回......但即使我干预这一和残酷地说“no,使它成为一个较小的猎物”,但似乎后来一些东西方都推翻了。

<代码>垂直头盔的最低条码似乎也没有效果。

我还认为,表格模型的<代码>数据()方法可能是专有的,但作用13“SizeHintRole”似乎从未发射过。

Source code
I have tried looking at the source code. The method of interest here seems to be on l. 3523, one of several versions of QHeaderView s resizeSections method. The code is naturally quite daunting, but I did spot, for example, invalidateCachedSizeHint() on l. 3261, which might explain why the size hints are being ignored... Anyone with particularly intricate knowledge of QHeaderView s functionality? Update later After Musicamante suggested use of setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContent) (good idea), I don t now know what part of the source code is involved.

Screenshot
main window

......单行浏览量略高。 如果你们看到一些不同的东西,就像完全紧缩的单行流一样,请让我知道。 页: 1 一位不同的顾问可能会产生不同的结果,谁知道?

问题回答

The problem is twofold, as resizing to contents means that the header queries its own size requirements and the view s:

  • the header s defaultSectionSize(), minimumSectionSize() and sectionSizeFromContents();
  • the view s sizeHintForRow() (or sizeHintForColumn() for horizontal headers), which eventually queries the delegate s sizeHint() function;

当观察只显示一条线时,这种风格(即上面点击的头脑功能)会恢复违约高度,而这种距离可能比所显示的案文更长。

如果能够打字并显示一个以上线,所展示的文字通常需要比头部最终使用的更垂直的空间,而空间则会因缺省而增加,从而导致比单行方式小的视力。

为了实现一致的转轨,你必须执行一个习惯头,从<条形码>中恢复很小的大小,并且应当为<条码>>的“dfault SectionSize和<条码>确定任意小的大小。 这样,这种观点将始终考虑到所展示案文的实际内容,其幅度将始终一致。

class VerticalHeader(QHeaderView):
    def __init__(self, parent):
        super().__init__(Qt.Vertical, parent)
        # we can set everything in here
        self.setSectionResizeMode(self.ResizeToContents)
        self.setDefaultSectionSize(1)
        self.setMinimumSectionSize(1)
        self.hide()

    def sectionSizeFromContents(self, index):
        size = super().sectionSizeFromContents(index)
        size.setHeight(1)
        return size

Note that sectionSizeFromContents() is also used to have the width of a modernheader, but since You re not showing the modernheader, a briefr return QSize( is means.

最后,你刚刚需要适当设立负责人;你不需要再在表格中超越<>代码>。

class LogTableView(QTableView):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # IMPORTANT! set the column count, so that we can automatically set 
        # the column widths
        self.setModel(QStandardItemModel(0, 3))
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.setAlternatingRowColors(True)

        self.horizontalHeader().setStretchLastSection(True)
        self.horizontalHeader().hide()
        self.setVerticalHeader(VerticalHeader(self))

        self.setColumnWidth(0, 160)
        self.setColumnWidth(1, 100)

    ...

作为无关的注解,如果方案逻辑需要使用数字价值,你就应避免将数字转换为指示数。 代表将在必要时自动将价值转换为指示数。

日期/时间数值也一样,因为它们可能要求适当执行(例如,分类或过滤):你只能使用适当的代表,以便<><>><>>>>。 页: 1

class DateDelegate(QStyledItemDelegate):
    def displayText(self, value, locale):
        if isinstance(value, QDateTime):
            return value.toString( ddd HH:mm:ss.zzz )
        return super().displayText(value, locale)


class LogTableView(QTableView):
    def __init__(self, *args, **kwargs):
        ... # as above

        self.setItemDelegateForColumn(0, DateDelegate(self))

    def visual_log(self, msg: str, log_level: int=logging.INFO):
        model = self.model()
        i_new_row = model.rowCount()
        model.insertRow(i_new_row)

        datetime_item = QStandardItem()
        datetime_item.setData(QDateTime.currentDateTime(), Qt.DisplayRole)
        model.setItem(i_new_row, 0, datetime_item)

        log_item = QStandardItem()
        log_item.setData(log_level, Qt.DisplayRole)
        model.setItem(i_new_row, 1, log_item)

        model.setItem(i_new_row, 2, QStandardItem(msg))





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签