当前位置: 首页>>代码示例>>Python>>正文


Python QTableView.resizeColumnsToContents方法代码示例

本文整理汇总了Python中PyQt5.QtWidgets.QTableView.resizeColumnsToContents方法的典型用法代码示例。如果您正苦于以下问题:Python QTableView.resizeColumnsToContents方法的具体用法?Python QTableView.resizeColumnsToContents怎么用?Python QTableView.resizeColumnsToContents使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt5.QtWidgets.QTableView的用法示例。


在下文中一共展示了QTableView.resizeColumnsToContents方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: SetupUI

# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import resizeColumnsToContents [as 别名]
    def SetupUI(self, w):
        info("SetupUI")

        # Search bar
        lblName = QLabel('Search')
        lblResults = QLabel('Results')

        # Plugin table
        ledtName = QLineEdit()
        tblResults = QTableView()
        tblResultsModel = PluginTableModel(self.available_plugins, Plugin.SQLITE_COLUMNS, w)
        tblResults.setModel( tblResultsModel )
        tblResults.horizontalHeader().setStretchLastSection(True)
        tblResults.verticalHeader().setVisible(False)
        tblResults.resizeColumnsToContents()
        tblResults.setSortingEnabled(True)
        tblResults.setFont( QFont("Courier New", 8) )
        tblResults.setShowGrid(False)

        ## event handlers
        ledtName.textChanged.connect(self.OnSearchFieldChange)


        # Button row
        btnUpdate = QPushButton("Refresh Plugins List")
        btnInstall = QPushButton("Install")

        ## event handlers
        btnUpdate.clicked.connect(self.RefreshPluginsList)
        btnInstall.clicked.connect(self.InstallSelected)


        grid = QGridLayout()
        grid.addWidget(lblName, 1, 0)
        grid.addWidget(ledtName, 1, 1)
        grid.addWidget(lblResults, 2, 0)
        grid.addWidget(tblResults, 2, 1, 5, 1)

        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addWidget(btnUpdate)
        vbox.addWidget(btnInstall)
        wButtons = QWidget()
        wButtons.setLayout(vbox)

        grid.addWidget(wButtons, 5, 1, 4, 1)
        w.setLayout(grid)
        return
开发者ID:hugsy,项目名称:stuff,代码行数:50,代码来源:IdaPluginManager.py

示例2: InvertedTable

# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import resizeColumnsToContents [as 别名]
class InvertedTable(SQLTable):
    """a Widget that displays content of an SQLite query inverted
    (= with rows and columns flipped);
    """
    def __init__(self, log, mydb = ": memory :", add_color_proxy = False):
        self.add_color_proxy = add_color_proxy
        super().__init__(log, mydb)
        self.fill_UI()
        
    def fill_UI(self):
        """sets up the layout
        """
        self.table = QTableView()
        header = self.table.horizontalHeader()
        header.hide()
        header.setStretchLastSection(True)
        self.table.resizeColumnsToContents()
        self.table.setAlternatingRowColors(True)
        self.grid.addWidget(self.table, 1, 0)
        self.log.debug("\t=> Table created!")
    
    def invert_model(self):
        """inverts the model for the table
        """
        self.flipped_model = GUI_flipped.FlippedProxyModel()
        if self.model:
            self.log.debug("Creating the flipped model...")
            if self.add_color_proxy:
                (allele_status_column, lab_status_column) = self.add_color_proxy
                self.log.debug("adding status color background to columns {} and {}".format(allele_status_column, lab_status_column))
                self.color_proxy = ColorProxyModel(self, allele_status_column, lab_status_column)
                self.color_proxy.setSourceModel(self.model)
                self.flipped_model.setSourceModel(self.color_proxy)
            else:
                self.flipped_model.setSourceModel(self.model)
            self.table.setModel(self.flipped_model)
            self.table.setItemDelegate(GUI_flipped.FlippedProxyDelegate(self.table)) # use flipped proxy delegate
            self.log.debug("\t=> Model created")
开发者ID:DKMS-LSL,项目名称:typeloader,代码行数:40,代码来源:GUI_overviews.py

示例3: MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import resizeColumnsToContents [as 别名]

#.........这里部分代码省略.........
        self.model2.setHeaderData(1, Qt.Horizontal, "개수")


    def setupViews(self):
        splitter = QSplitter()
        self.table = QTableView()
        self.pieChart = PieView()


        splitter.addWidget(self.pieChart)
        splitter.addWidget(self.table)
        splitter.setStretchFactor(0, 0)
        splitter.setStretchFactor(1, 0)

        self.table.setModel(self.model)
        self.pieChart.setModel(self.model2)

        self.selectionModel = QItemSelectionModel(self.model2)
        self.table.setSelectionModel(self.selectionModel)

        #self.pieChart.setSelectionModel(self.selectionModel)

        #table.setColumnWidth(0,100)
        self.setCentralWidget(splitter)
        self.table.doubleClicked.connect(self.ClickAction_table)

    def readDB(self):

        con = sqlite3.connect("mystudy.db")
        cur = con.cursor()
        cur.execute("select subject, readcheck from study;")
        self.model.removeRows(0, self.model.rowCount(QModelIndex()),
                        QModelIndex())
        self.model2.removeRows(0, self.model2.rowCount(QModelIndex()),
                        QModelIndex())
        row = 0
        for line in cur:
            if line[1] ==1:
                result = "○"
            else:
                result = "X"
            self.model.insertRows(row, 1, QModelIndex())
            self.model.setData(self.model.index(row, 0, QModelIndex()), line[0])
            self.model.setData(self.model.index(row, 1, QModelIndex()),result)
            self.model.setData(self.model.index(row, 1, QModelIndex()), QVariant(Qt.AlignCenter),Qt.TextAlignmentRole)
            row += 1
        cur.execute("select count() from study ;")
        for line in cur:
            self.studyTotal =line[0]
        cur.execute("select count() from study where readcheck=1;")
        for line in cur:
            self.studyRead =line[0]
        #print("총 개수 " ,self.studyTotal ," 학습한개수", self.studyRead )
        con.close()
        row=0
        self.model2.insertRows(row, 1, QModelIndex())
        self.model2.setData(self.model2.index(row, 0, QModelIndex()),"학습")
        self.model2.setData(self.model2.index(row, 1, QModelIndex()), float(self.studyRead))
        self.model2.setData(self.model2.index(row, 0, QModelIndex()), QColor("#99e600"), Qt.DecorationRole)
        row=1
        self.model2.insertRows(row, 1, QModelIndex())
        self.model2.setData(self.model2.index(row, 0, QModelIndex()),"미학습")
        self.model2.setData(self.model2.index(row, 1, QModelIndex()), float(self.studyTotal-self.studyRead))
        self.model2.setData(self.model2.index(row, 0, QModelIndex()), QColor("#8080b3"), Qt.DecorationRole)


        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.table.setDragEnabled(False)
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table.resizeRowsToContents()
        self.table.resizeColumnsToContents()
        self.table.setColumnWidth(0,350)
                    #self.statusBar().showMessage("Loaded %s" % path, 2000)
    def ClickAction_table(self,index):
        #self.system
        #index.data()
        #self.table.selectedIndexes()[0].data()
        tempstr = self.table.selectedIndexes()[0].data().split()
        filepath = r"PyStudy_web\\example\\기본예제\\"+tempstr[0]+".html"
        selectedRowKey = self.table.selectedIndexes()[0].row()+1#mysql 테이블 줄수 차이
        #print("click test ",selectedRowKey )
        con = sqlite3.connect("mystudy.db")
        cur = con.cursor()
        cur.execute("update 'study' set 'readcheck'=1 where key="+str(selectedRowKey)+";")
        con.commit()
        con.close()
        self.setupViews()
        self.readDB()

        self.system.sendMessage("/학습창 열기 "+filepath)
    def ClickAction_dbinit(self,index):
        con = sqlite3.connect("mystudy.db")
        cur = con.cursor()
        cur.execute("update 'study' set 'readcheck'=0 ;")
        con.commit()
        con.close()
        self.setupViews()
        self.readDB()
开发者ID:louisraccoon,项目名称:PyStudy,代码行数:104,代码来源:StudyPlan.py

示例4: MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import resizeColumnsToContents [as 别名]

#.........这里部分代码省略.........

        self.setWindowTitle("Pixelator")
        self.resize(640, 480)

    def chooseImage(self):
        fileName, _ = QFileDialog.getOpenFileName(self, "Choose an Image",
                self.currentPath, '*')

        if fileName:
            self.openImage(fileName)

    def openImage(self, fileName):
        image = QImage()

        if image.load(fileName):
            self.model.setImage(image)

            if not fileName.startswith(':/'):
                self.currentPath = fileName
                self.setWindowTitle("%s - Pixelator" % self.currentPath)

            self.printAction.setEnabled(True)
            self.updateView()

    def printImage(self):
        if self.model.rowCount(QModelIndex()) * self.model.columnCount(QModelIndex()) > 90000:
            answer = QMessageBox.question(self, "Large Image Size",
                    "The printed image may be very large. Are you sure that "
                    "you want to print it?",
                    QMessageBox.Yes | QMessageBox.No)
            if answer == QMessageBox.No:
                return

        printer = QPrinter(QPrinter.HighResolution)

        dlg = QPrintDialog(printer, self)
        dlg.setWindowTitle("Print Image")

        if dlg.exec_() != QDialog.Accepted:
            return

        painter = QPainter()
        painter.begin(printer)

        rows = self.model.rowCount(QModelIndex())
        columns = self.model.columnCount(QModelIndex())
        sourceWidth = (columns+1) * ItemSize
        sourceHeight = (rows+1) * ItemSize

        painter.save()

        xscale = printer.pageRect().width() / float(sourceWidth)
        yscale = printer.pageRect().height() / float(sourceHeight)
        scale = min(xscale, yscale)

        painter.translate(printer.pageRect().x()+printer.pageRect().width()/2,
                          printer.pageRect().y()+printer.pageRect().height()/2)
        painter.scale(scale, scale)
        painter.translate(-sourceWidt/2, -sourceHeight/2)

        option = QStyleOptionViewItem()
        parent = QModelIndex()

        progress = QProgressDialog("Printing...", "Cancel", 0, rows, self)
        y = ItemSize / 2.0

        for row in range(rows):
            progress.setValue(row)
            QApplication.processEvents()
            if progress.wasCanceled():
                break

            x = ItemSize / 2.0

            for col in range(columns):
                option.rect = QRect(x, y, ItemSize, ItemSize)
                self.view.itemDelegate.paint(painter, option,
                        self.model.index(row, column, parent))
                x = x + ItemSize

            y = y + ItemSize

        progress.setValue(rows)

        painter.restore()
        painter.end()

        if progress.wasCanceled():
            QMessageBox.information(self, "Printing canceled",
                    "The printing process was canceled.", QMessageBox.Cancel)

    def showAboutBox(self):
        QMessageBox.about(self, "About the Pixelator example",
                "This example demonstrates how a standard view and a custom\n"
                "delegate can be used to produce a specialized "
                "representation\nof data in a simple custom model.")

    def updateView(self):
        self.view.resizeColumnsToContents()
        self.view.resizeRowsToContents()
开发者ID:heylenz,项目名称:python27,代码行数:104,代码来源:pixelator.py

示例5: GoodreadsOptionsForm

# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import resizeColumnsToContents [as 别名]
class GoodreadsOptionsForm(QDialog):
    def __init__(self, user_id):
        super(GoodreadsOptionsForm, self).__init__()
        self.initUI(self)
        self.user_id = user_id

    def initUI(self, GoodreadsOptionsForm):
        layout = QGridLayout(self)

        self.main_label = QLabel("Please choose an option:")
        self.search_combo_box = QComboBox()
        self.search_combo_box.addItem("Read")
        self.search_combo_box.addItem("Currently Reading")
        self.search_combo_box.addItem("To-Read")
        self.search_button = QPushButton("Search")

        layout.addWidget(self.main_label, 0, 0)
        layout.addWidget(self.search_combo_box, 0, 1)
        layout.addWidget(self.search_button, 0, 2, 1, 2)

        self.setLayout(layout)
        self.search_button.clicked.connect(self.search_button_click)
        self.layout().setSizeConstraint(QLayout.SetFixedSize)
        self.setWindowTitle("Search Books")
        self.setWindowIcon(QIcon(QPixmap('../images/search.png')))

    def show_user_shelf(self, user_id, shelf):
        goodreads_shelf = shelf
        client = GoodReadsClient(KEY, SECRET)
        books = client.get_shelf(user_id, goodreads_shelf)
        view_books = []

        for book in books:
            isbn = book["isbn"]
            title = book["title"]
            goodreads_url = book["link"]
            year = book["published"]
            author = book["authors"][0]["name"]
            rating = book["average_rating"]
            view_books.append((isbn, title, author, year,
                               rating, goodreads_url))

        if view_books != []:
            book_model = GoodReadsBookModel()
            view_books = [GoodReadsBook(*book) for book in view_books]
            book_model.set_books(view_books)
            self.show_table(book_model)
        else:
            QMessageBox(QMessageBox.Information, "No results",
                        "Sorry. There are no results found!").exec_()

    def show_table(self, model):
        self.table = QTableView()
        self.table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
        self.model = model
        self.table.setWindowTitle("Books")
        self.table.setWindowIcon(QIcon(QPixmap('../images/icon.png')))
        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.table.show()

    def search_button_click(self):
        option = self.search_combo_box.currentText()
        shelf = ""
        if option == 'Read':
            shelf = "read"
        elif option == 'Currently Reading':
            shelf = "currently-reading"
        elif option == 'To-Read':
            shelf = "to-read"

        self.show_user_shelf(self.user_id, shelf)
开发者ID:DenitsaKostova,项目名称:Bookoholic,代码行数:74,代码来源:goodreads_option.py

示例6: main

# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import resizeColumnsToContents [as 别名]
def main(icon_spec):
    app = QApplication(sys.argv)

    main_window = QMainWindow()

    def sigint_handler(*args):
        main_window.close()
    signal.signal(signal.SIGINT, sigint_handler)
    # the timer enables triggering the sigint_handler
    signal_timer = QTimer()
    signal_timer.start(100)
    signal_timer.timeout.connect(lambda: None)

    tool_bar = QToolBar()
    main_window.addToolBar(Qt.TopToolBarArea, tool_bar)

    table_view = QTableView()
    table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
    table_view.setSelectionMode(QAbstractItemView.SingleSelection)
    table_view.setSortingEnabled(True)
    main_window.setCentralWidget(table_view)

    proxy_model = QSortFilterProxyModel()
    proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
    proxy_model.setFilterKeyColumn(1)
    table_view.setModel(proxy_model)
    proxy_model.layoutChanged.connect(table_view.resizeRowsToContents)

    item_model = QStandardItemModel()
    proxy_model.setSourceModel(item_model)

    # get all icons and their available sizes
    icons = []
    all_sizes = set([])
    for context, icon_names in icon_spec:
        for icon_name in icon_names:
            icon = QIcon.fromTheme(icon_name)
            sizes = []
            for size in icon.availableSizes():
                size = (size.width(), size.height())
                sizes.append(size)
                all_sizes.add(size)
            sizes.sort()
            icons.append({
                'context': context,
                'icon_name': icon_name,
                'icon': icon,
                'sizes': sizes,
            })
    all_sizes = list(all_sizes)
    all_sizes.sort()

    # input field for filter
    def filter_changed(value):
        proxy_model.setFilterRegExp(value)
        table_view.resizeRowsToContents()
    filter_line_edit = QLineEdit()
    filter_line_edit.setMaximumWidth(200)
    filter_line_edit.setPlaceholderText('Filter name')
    filter_line_edit.setToolTip('Filter name optionally using regular expressions (' + QKeySequence(QKeySequence.Find).toString() + ')')
    filter_line_edit.textChanged.connect(filter_changed)
    tool_bar.addWidget(filter_line_edit)

    # actions to toggle visibility of available sizes/columns 
    def action_toggled(index):
        column = 2 + index
        table_view.setColumnHidden(column, not table_view.isColumnHidden(column))
        table_view.resizeColumnsToContents()
        table_view.resizeRowsToContents()
    signal_mapper = QSignalMapper()
    for i, size in enumerate(all_sizes):
        action = QAction('%dx%d' % size, tool_bar)
        action.setCheckable(True)
        action.setChecked(True)
        tool_bar.addAction(action)
        action.toggled.connect(signal_mapper.map)
        signal_mapper.setMapping(action, i)
        # set tool tip and handle key sequence
        tool_tip = 'Toggle visibility of column'
        if i < 10:
            digit = ('%d' % (i + 1))[-1]
            tool_tip += ' (%s)' % QKeySequence('Ctrl+%s' % digit).toString()
        action.setToolTip(tool_tip)
    signal_mapper.mapped.connect(action_toggled)

    # label columns
    header_labels = ['context', 'name']
    for width, height in all_sizes:
        header_labels.append('%dx%d' % (width, height))
    item_model.setColumnCount(len(header_labels))
    item_model.setHorizontalHeaderLabels(header_labels)

    # fill rows
    item_model.setRowCount(len(icons))
    for row, icon_data in enumerate(icons):
        # context
        item = QStandardItem(icon_data['context'])
        item.setFlags(item.flags() ^ Qt.ItemIsEditable)
        item_model.setItem(row, 0, item)
        # icon name
#.........这里部分代码省略.........
开发者ID:dirk-thomas,项目名称:qt_theme_icons,代码行数:103,代码来源:icons.py


注:本文中的PyQt5.QtWidgets.QTableView.resizeColumnsToContents方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。